Injecting Mocks with @Mock and @InjectMocks
Use Mockito annotations to wire mocked dependencies into the class under test, reducing boilerplate setup code.
Why Annotations?
Creating mocks manually with mock(Type.class) works, but for classes with several dependencies it becomes repetitive. Mockito offers annotations that declare and wire mocks for you.
@Mockdeclares a mock field@InjectMocksbuilds the real object and injects the mocks
The Class Under Test
Imagine an OrderService that depends on a PaymentGateway. We want to test the service while controlling the gateway.
class OrderService {
private final PaymentGateway gateway;
OrderService(PaymentGateway gateway) { this.gateway = gateway; }
boolean checkout(double amount) {
return gateway.charge(amount);
}
}All lessons in this course
- Mocks, Stubs, and Fakes
- Creating Mocks with Mockito
- Verifying Mock Interactions
- Injecting Mocks with @Mock and @InjectMocks