How do you combine JUnit and Mockito to write comprehensive unit tests?

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

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.

@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.

Last updated: 16 July 2026

Previous question: How do you mock behavior for methods that depend on randomness (like Math.random())?

More Mockito interview questions

All Mockito questions