0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Lesson

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.

  • @Mock declares a mock field
  • @InjectMocks builds 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

  1. Mocks, Stubs, and Fakes
  2. Creating Mocks with Mockito
  3. Verifying Mock Interactions
  4. Injecting Mocks with @Mock and @InjectMocks
← Back to Testing Mastery: JUnit, Mockito & Integration Tests