Injecting Mocks with @Mock and @InjectMocks
Use Mockito annotations to wire mocked dependencies into the class under test, reducing boilerplate setup code.
Injecting Mocks with @Mock and @InjectMocks is a free Testing Mastery: JUnit, Mockito & Integration Tests lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Testing Mastery: JUnit, Mockito & Integration Tests learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
}
}Declaring a @Mock
Annotate a field with @Mock and Mockito creates a mock instance for it automatically once the annotations are processed.
@Mock
PaymentGateway gateway;Using @InjectMocks
@InjectMocks tells Mockito to instantiate the target and inject any @Mock fields into it, via constructor, setter, or field injection.
@Mock PaymentGateway gateway;
@InjectMocks OrderService service;Activating the Annotations
Annotations do nothing on their own. With JUnit 5 you enable them using @ExtendWith(MockitoExtension.class) on the test class.
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock PaymentGateway gateway;
@InjectMocks OrderService service;
}The Older openMocks Approach
Without the extension you can call MockitoAnnotations.openMocks(this) in a @BeforeEach method. Prefer the extension when you can.
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}Writing the Test
Now stub the injected mock and exercise the service. The service already holds the mocked gateway, so no manual wiring is needed.
@Test
void checkoutSucceeds() {
when(gateway.charge(100.0)).thenReturn(true);
assertTrue(service.checkout(100.0));
}Injection Strategies
Mockito tries injection in this order:
- Constructor injection (preferred)
- Setter injection
- Field injection
Constructor injection is the safest because it works with final fields.
Multiple Dependencies
A class with several collaborators just gets several @Mock fields. Mockito matches each by type during injection.
@Mock PaymentGateway gateway;
@Mock InventoryRepo inventory;
@InjectMocks OrderService service;When Injection Fails Silently
If a dependency cannot be matched, the field stays null rather than throwing. A NullPointerException at test time often means injection did not happen as expected. Verify types and constructor signatures.
Cleaner Tests
Annotations remove repetitive mock(...) and new Service(...) calls, keeping each test focused on behavior instead of wiring.
Quick Check
Which annotation builds the real object and injects mocks into it?
Recap
You learned to wire mocks declaratively:
@Mockdeclares a mock field@InjectMocksbuilds the target and injects mocks- Enable with
@ExtendWith(MockitoExtension.class) - Constructor injection is preferred and supports final fields
Frequently asked questions
Is the “Injecting Mocks with @Mock and @InjectMocks” lesson free?
Yes — the full text of “Injecting Mocks with @Mock and @InjectMocks” is free to read here on the web, and the Testing Mastery: JUnit, Mockito & Integration Tests course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Testing Mastery: JUnit, Mockito & Integration Tests course, upgrade to CoddyKit PRO.
What will I learn in “Injecting Mocks with @Mock and @InjectMocks”?
Use Mockito annotations to wire mocked dependencies into the class under test, reducing boilerplate setup code. You practise Testing Mastery: JUnit, Mockito & Integration Tests with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Testing Mastery: JUnit, Mockito & Integration Tests?
No prior experience is required. Testing Mastery: JUnit, Mockito & Integration Tests on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Injecting Mocks with @Mock and @InjectMocks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Testing Mastery: JUnit, Mockito & Integration Tests lesson?
Yes. Every Testing Mastery: JUnit, Mockito & Integration Tests lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Mocks, Stubs, and Fakes
- Creating Mocks with Mockito
- Verifying Mock Interactions
- Injecting Mocks with @Mock and @InjectMocks