How do you mock objects in Mockito when using constructor injection?

Constructor injection makes mocking straightforward in Mockito: you create mocks for each dependency, then pass them directly into the constructor of the class under test.

Key Points: • Use mock(Dependency.class) for each collaborator the class needs. • Instantiate the class under test by calling its constructor with the mocks, e.g. new OrderService(mockRepo, mockMailer). • With @Mock and @InjectMocks plus @ExtendWith(MockitoExtension.class), Mockito can wire constructor mocks automatically. • This approach forces the class to depend on abstractions passed in, which is what makes it easily testable in isolation. • No reflection or field hacking is needed, unlike mocking dependencies injected via field or setter injection.

Example: For a class OrderService(PaymentGateway gateway, InventoryClient inventory), a test simply builds mock(PaymentGateway.class) and mock(InventoryClient.class) and constructs OrderService with them before stubbing behavior.

Code Example:

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock
    private PaymentGateway gateway;

    @Mock
    private InventoryClient inventory;

    @InjectMocks
    private OrderService orderService;

    @Test
    void placesOrderWhenPaymentSucceeds() {
        when(gateway.charge(anyDouble())).thenReturn(true);
        assertTrue(orderService.placeOrder("SKU-1", 2));
    }
}

Interview Tip: A concise interview answer is:

"With constructor injection I mock each dependency with mock(), then construct the class under test with those mocks directly, or let @Mock plus @InjectMocks wire them automatically. It's the cleanest form of dependency injection to test because there's no field reflection involved."