Get ready for your next interview with our comprehensive question library
Mockito is a popular Java mocking framework used for unit testing. It allows developers to create mock objects that simulate the behavior of real objects in a controlled way. The main purposes of Mockito are:
Mockito helps create fast, reliable, and focused unit tests by eliminating external dependencies.
Maven:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
Gradle:
testImplementation 'org.mockito:mockito-core:5.7.0'
JUnit 5 integration:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
There are several ways to create mocks in Mockito:
List<String> mockList = mock(List.class);
@Mock
private List<String> mockList;
@MockBean
private UserService userService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
The annotation approach is preferred as it makes tests cleaner and more readable.
Mockito provides the verify() method to check if methods were called:
// Verify method was called once
verify(mockList).add("item");
// Verify method was called specific number of times
verify(mockList, times(2)).add(anyString());
// Verify method was never called
verify(mockList, never()).clear();
// Verify method was called at least/at most certain times
verify(mockList, atLeast(1)).size();
verify(mockList, atMost(3)).add(anyString());
Verification should be done after the method under test has been executed.
Upgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumAccess all premium content - interview questions, and other learning resources
We regularly update our features and content, to ensure you get the most relevant and updated premium content.
1000 monthly credits
Cancel anytime