How to Use @Mock Annotation in JUnit for Unit Testing
Use the
@Mock annotation in JUnit tests to create mock objects that simulate dependencies. Annotate fields with @Mock and initialize them with MockitoAnnotations.openMocks(this) in a setup method to use mocks in your tests.Syntax
The @Mock annotation is used to declare a mock object in your test class. You place it above a field that you want to mock. To activate these mocks, you call MockitoAnnotations.openMocks(this) in a method annotated with @BeforeEach in JUnit 5 or @Before in JUnit 4.
This setup tells Mockito to create mock instances for all fields annotated with @Mock.
java
import org.junit.jupiter.api.BeforeEach; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class MyTest { @Mock private MyService myService; private AutoCloseable closeable; @BeforeEach void setUp() { closeable = MockitoAnnotations.openMocks(this); } // test methods here @AfterEach void tearDown() throws Exception { closeable.close(); } }
Example
This example shows how to use @Mock to mock a dependency and verify its interaction in a JUnit 5 test.
java
import static org.mockito.Mockito.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class UserServiceTest { @Mock private UserRepository userRepository; private UserService userService; private AutoCloseable closeable; @BeforeEach void setUp() { closeable = MockitoAnnotations.openMocks(this); userService = new UserService(userRepository); } @Test void testGetUserById() { when(userRepository.findById(1)).thenReturn(new User(1, "Alice")); User user = userService.getUserById(1); assert user != null; assert user.getName().equals("Alice"); verify(userRepository).findById(1); } @AfterEach void tearDown() throws Exception { closeable.close(); } } class UserService { private final UserRepository userRepository; UserService(UserRepository userRepository) { this.userRepository = userRepository; } User getUserById(int id) { return userRepository.findById(id); } } interface UserRepository { User findById(int id); } class User { private final int id; private final String name; User(int id, String name) { this.id = id; this.name = name; } int getId() { return id; } String getName() { return name; } }
Output
Test passed with no errors
Common Pitfalls
- Forgetting to initialize mocks with
MockitoAnnotations.openMocks(this)causesNullPointerExceptionbecause mocks are not created. - Using
@Mockwithout Mockito dependency or import will cause compilation errors. - Not using
verify()orwhen()properly can lead to tests that do not actually test behavior. - Mixing JUnit 4 and JUnit 5 annotations can cause lifecycle methods not to run.
java
/* Wrong way: Missing initialization */ import org.junit.jupiter.api.Test; import org.mockito.Mock; class WrongTest { @Mock private MyService myService; @Test void test() { // myService is null here, test will fail myService.doSomething(); } } /* Right way: Initialize mocks */ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class RightTest { @Mock private MyService myService; private AutoCloseable closeable; @BeforeEach void setUp() { closeable = MockitoAnnotations.openMocks(this); } @Test void test() { myService.doSomething(); // works fine } @AfterEach void tearDown() throws Exception { closeable.close(); } }
Quick Reference
- @Mock: Declares a mock object.
- MockitoAnnotations.openMocks(this): Initializes mocks before each test.
- when(...).thenReturn(...): Defines mock behavior.
- verify(...): Checks if mock methods were called.
Key Takeaways
Always initialize @Mock annotated fields with MockitoAnnotations.openMocks(this) before tests run.
Use @Mock to create mock objects that simulate dependencies in unit tests.
Define mock behavior with when(...).thenReturn(...) and verify interactions with verify(...).
Mixing JUnit versions or missing Mockito setup causes common errors like NullPointerException.
Keep your test setup clean and consistent to ensure mocks work correctly.