JUnit Essentials
JUnit is a unit testing framework for Java. A unit test should verify one behavior in isolation and be fast enough to run often.
Common JUnit 4 annotations:
| Annotation | Purpose |
|---|---|
@Test | Marks a test method |
@Before | Runs before each test |
@After | Runs after each test |
@BeforeClass | Runs once before all tests |
@AfterClass | Runs once after all tests |
Common assertions include assertEquals, assertTrue, assertFalse, assertNull, and assertNotNull.
Mock vs Spy
A mock is a fully fake object. By default it does not call real behavior. A spy wraps a real object; unstubbed methods call real behavior.
Use mocks for external collaborators. Use spies carefully when partial real behavior is useful but you still need to stub a small part.
Interview Scenario Practice
Scenario 1: Mock External Payment Client
Scenario: Your service calls a payment gateway, but the unit test should not hit the real provider.
Strong answer: Mock the payment client and verify how the service behaves for success, failure, and timeout responses.
Why it works: Unit tests should be fast, deterministic, and isolated from external systems.
Common mistake: Calling real third-party services from unit tests, making tests slow and flaky.
Scenario 2: Mock vs Spy
Scenario: You need most real behavior from an object but want to stub one method.
Strong answer: A spy can wrap a real object and stub specific methods, while unstubbed methods still call real behavior.
Why it works: Spies are useful for partial substitution, but they should be used carefully because real methods may have side effects.
Common mistake: Using spies everywhere instead of designing smaller units with clear dependencies.
Scenario 3: Setup Repeated Before Tests
Scenario: Each test needs a fresh object with clean state.
Strong answer: Use per-test setup such as JUnit 4 @Before or JUnit 5 @BeforeEach.
Why it works: Fresh setup prevents one test's mutation from affecting another test.
Common mistake: Sharing mutable test state across tests and creating order-dependent failures.