Mockito is an open-source mocking framework used for unit testing in Java. It allows developers to create mock objects (fake objects) that simulate the behavior of real dependencies. By replacing real objects with mocks, Mockito helps test code in isolation without calling actual databases, APIs, or external services.
- Faster Tests: Avoid slow operations like database or network calls.
- Cleaner Code: Reduce boilerplate with annotations like @Mock and @InjectMocks.
Core Concepts of Mockito
1. Mock Objects
Mock objects are fake implementations of real objects used during testing. They allow testing a class independently by replacing its dependencies.
2. Stubbing
Stubbing defines what a mock object should return when a method is called. It can return fixed values or throw exceptions.
Example:
when(repository.findById(1)).thenReturn(user);
3. Verification
Verification checks whether certain methods were called during test execution.
Example:
verify(repository).save(user);
Common Annotations in Mockito
| Annotation | Features |
|---|---|
@ExtendWith(MockitoExtension.class) | Enables Mockito support in **JUnit 5 test classes and allows use of Mockito annotations like @Mock, @InjectMocks, and @Spy. |
@Mock | Creates a mock (fake) object automatically for testing without calling mock(Class.class) manually. |
@InjectMocks | Creates an instance of the class under test and automatically injects @Mock objects into it. |
@Spy | Creates a partial mock using a real object but allows overriding specific methods when needed. |
Common Mockito Methods
Mockito provides several built-in methods that help developers control and verify the behavior of mock objects during testing. These methods are mainly used for stubbing method responses and verifying interactions between objects.
1. when().thenReturn()
Used for stubbing method calls to return specific values.
when(mockList.get(0)).thenReturn("First Element");
when(mockList.size()).thenReturn(5);
2. when().thenThrow()
Used for stubbing method calls to throw exceptions.
when(mockList.get(anyInt())).thenThrow(new RuntimeException("Error"));
3. verify()
Used to verify that certain methods were called.
verify(mockList).add("Element");
verify(mockList, times(2)).size();
verify(mockList, never()).clear();
4. Argument Matchers
Mockito provides argument matchers for flexible method matching.
Common Argument Matchers:
- any(): Matches any object
- anyInt(): Matches any integer
- anyString(): Matches any string
- isNull(): Matches null values
Setting Up Mockito
Step 1: Create a Project
Create a Java / Spring Boot project using Maven or Gradle where the test cases will be written.
Step 2: Add JUnit Dependency
JUnit is required to run test cases.
Maven(pom.xml)
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
Step 3: Add Mockito Core Dependency
Add Mockito library to create mock objects.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
Step 4: Add Mockito JUnit Extension
Required for using annotations like @Mock and @InjectMocks.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
Step 5: Enable Mockito in Test Class
Enable Mockito annotations in the test class.
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
}
Step 6: Create Mock Objects
@Mock
UserRepository repository;
@InjectMocks
UserService service;
@Mock->Creates fake dependency.@InjectMocks->Injects mock objects into the class being tested.
Step 7: Write a Test Case
@Test
void testGetUser() {
when(repository.findById(1)).thenReturn(new User("John"));
User result = service.getUser(1);
assertEquals("John", result.getName());
}
- when().thenReturn() ->defines mock behavior.
- assertEquals() ->verifies the result.