Java
@Mock
Learn mock injection with @Mock.
@Mock
The @Mock annotation marks a field as a mock. This is shorter than calling mock(). Mocks are initialized with MockitoAnnotations.openMocks(this).
class UserServiceTest {
@Mock UserRepository repo;
@Mock MailService mail;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
}
}
When many mocks are needed, this approach is more readable. The mock types are visible at a glance from the field declarations. This is the recommended way to use modern Mockito.
@InjectMocks
@InjectMocks automatically injects mocks into the class under test. It tries constructor, setter or field injection to wire up the dependencies.
@InjectMocks UserService service;
// service is injected with the @Mock repo and mail above
This saves writing new UserService(repo, mail) by hand. Even if the dependency structure changes, the test does not need an update. This is a key convenience for clean test code.
Exercise Build UserService with its dependency
Define a Logger interface (void log(String msg)). Define a UserService class whose constructor takes a Logger logger and whose greet(String name) method calls logger.log("Hello " + name). In an InjectDemo class write a main method; write a concrete Logger implementation, build the service with new UserService(logger) and call greet("Alex").
Show example solution
interface Logger {
void log(String msg);
}
class ConsoleLogger implements Logger {
public void log(String msg) {
System.out.println(msg);
}
}
class UserService {
Logger logger;
UserService(Logger logger) { this.logger = logger; }
void greet(String name) {
logger.log("Hello " + name);
}
}
class InjectDemo {
public static void main(String[] args) {
UserService s = new UserService(new ConsoleLogger());
s.greet("Alex");
}
}
Test yourself
-
Complete the Mock annotation
class UserServiceTest {
____ UserRepository repo;
@Mock MailService mail;
}
Show answer
class UserServiceTest {
@Mock UserRepository repo;
@Mock MailService mail;
}
-
What does @InjectMocks do?
- Creates mocks
- Injects mocks into the class under test
- Produces a test report
- Runs the test
Show answer
Injects mocks into the class under test — @InjectMocks wires mocks into the class under test.
-
Match Mockito annotations
- @Mock
- Fake object field
- @InjectMocks
- Injects mocks into a class
- @Spy
- Wraps a real object
- @Captor
- Argument captor
Next lesson: when thenReturn