@Mock
- Java course
- Advanced
- Lesson 50/82
- 5 min
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 aboveThis 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.
Practice 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").
Starter code
// Define the Logger interface (log method)
// Define a concrete Logger implementation
// Define the UserService class (constructor takes Logger, has greet)
// Write main in InjectDemo and print greet's outputSample 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");
}
}Expected output
Hello Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Mock annotation
class UserServiceTest {
____ UserRepository repo;
@Mock MailService mail;
}
class UserServiceTest {
@Mock UserRepository repo;
@Mock MailService mail;
}
Explanation: @Mock marks a field as a mock.
2 What does @InjectMocks do?
- Creates mocks
- Injects mocks into the class under test Correct answer
- Produces a test report
- Runs the test
Explanation: @InjectMocks wires mocks into the class under test.
3 Match Mockito annotations
| Term | Meaning |
|---|---|
@Mock |
Fake object field |
@InjectMocks |
Injects mocks into a class |
@Spy |
Wraps a real object |
@Captor |
Argument captor |