The @InjectMocks annotation helps automatically create and inject mock objects into the class you want to test. It saves time and makes tests cleaner.
0
0
@InjectMocks annotation in JUnit
Introduction
When you want to test a class that depends on other classes or services.
When you want to avoid manually creating and injecting mock objects.
When you want to focus on testing the main class behavior without real dependencies.
When you want to keep your test code simple and easy to read.
Syntax
JUnit
@InjectMocks private ClassToTest classToTest;
This annotation is used together with @Mock or @Spy annotations.
Mockito will create an instance of ClassToTest and inject mocks into it.
Examples
This creates a mock for
Dependency and injects it into Service automatically.JUnit
@Mock private Dependency dependency; @InjectMocks private Service service;
This creates a spy for
Helper and injects it into Controller.JUnit
@Spy private Helper helper; @InjectMocks private Controller controller;
Sample Program
This test uses @InjectMocks to create a Calculator instance with a mocked Adder. The test checks that the add method returns the mocked value.
JUnit
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class Calculator { private Adder adder; public Calculator(Adder adder) { this.adder = adder; } public int add(int a, int b) { return adder.add(a, b); } } interface Adder { int add(int x, int y); } public class CalculatorTest { @Mock Adder adder; @InjectMocks Calculator calculator; public CalculatorTest() { MockitoAnnotations.openMocks(this); } @Test void testAdd() { when(adder.add(2, 3)).thenReturn(5); int result = calculator.add(2, 3); assert result == 5 : "Expected 5 but got " + result; System.out.println("Test passed: " + (result == 5)); } }
OutputSuccess
Important Notes
Always initialize mocks with MockitoAnnotations.openMocks(this) or use @ExtendWith(MockitoExtension.class) in JUnit 5.
@InjectMocks tries to inject mocks by constructor, setter, or field injection in that order.
Summary
@InjectMocks creates the class under test and injects mocks automatically.
It reduces manual setup and keeps tests clean.
Works well with @Mock and @Spy annotations.