JUnit and Mockito work together by letting JUnit drive test structure and lifecycle while Mockito supplies and controls the mock dependencies each test needs.
Key Points: • Annotate the test class with @ExtendWith(MockitoExtension.class) so JUnit 5 initializes Mockito annotations automatically. • Use @Mock to create dependency mocks and @InjectMocks to wire them into the class under test. • Stub behavior with when()/thenReturn() before invoking the method under test. • Use JUnit's assertions (assertEquals, assertThrows, etc.) to verify return values, and Mockito's verify() to verify interactions. • Keep each @Test method focused on one scenario - one stubbing setup, one action, one set of assertions.
Example: A test for OrderService.placeOrder() might mock PaymentGateway and InventoryClient, stub them to simulate a successful payment, call placeOrder(), then assert the returned order status with JUnit and verify the payment was charged with Mockito.
Code Example:
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock private PaymentGateway gateway;
@InjectMocks private OrderService orderService;
@Test
void confirmsOrderWhenPaymentSucceeds() {
when(gateway.charge(50.0)).thenReturn(true);
assertTrue(orderService.placeOrder(50.0));
verify(gateway).charge(50.0);
}
}Interview Tip: A concise interview answer is:
"JUnit provides the test runner, lifecycle annotations, and assertions, while Mockito supplies mock dependencies via @Mock and @InjectMocks. I stub behavior with when()/thenReturn(), exercise the method under test, then combine JUnit assertions on the result with Mockito's verify() on interactions."