🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The verify() method in Mockito is used to check if certain methods on mock objects were called with specific arguments. This is particularly useful for verifying interactions and ensuring that the code under test is correctly interacting with its dependencies. This tutorial will demonstrate how to use the verify() method in Mockito to check method invocations.
Maven Dependencies
To use Mockito with JUnit 5, add the following dependencies to your pom.xml file:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
Example Scenario
We will create a UserService class that has a dependency on a UserRepository. Our goal is to test the UserService methods using the verify() method in Mockito to check if the interactions with the UserRepository are as expected.
UserService and UserRepository Classes
First, create the User class, the UserRepository interface, and the UserService class.
public class User {
private String name;
private String email;
// Constructor, getters, and setters
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public interface UserRepository {
void saveUser(User user);
User findUserByEmail(String email);
}
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void registerUser(String name, String email) {
User user = new User(name, email);
userRepository.saveUser(user);
}
public User getUserByEmail(String email) {
return userRepository.findUserByEmail(email);
}
}
JUnit 5 Test Class with Mockito
Create a test class for UserService using JUnit 5 and Mockito.
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
public void testRegisterUser() {
// Given
String name = "John Doe";
String email = "john.doe@example.com";
// When
userService.registerUser(name, email);
// Then
verify(userRepository).saveUser(new User(name, email));
}
@Test
public void testGetUserByEmail() {
// Given
String email = "jane.doe@example.com";
User user = new User("Jane Doe", email);
when(userRepository.findUserByEmail(email)).thenReturn(user);
// When
User result = userService.getUserByEmail(email);
// Then
assertNotNull(result);
assertEquals("Jane Doe", result.getName());
assertEquals(email, result.getEmail());
verify(userRepository).findUserByEmail(email);
}
}
Explanation
- The
@Mockannotation creates a mock instance of theUserRepositoryinterface. This mock instance can be used to simulate the behavior of theUserRepositoryin a controlled way. - The
@InjectMocksannotation injects the mockUserRepositoryinto theUserServiceinstance to provide a controlled test environment. This allows theUserServicemethods to be tested in isolation from the actualUserRepositoryimplementation. - The
verify(userRepository).saveUser(new User(name, email));method checks if thesaveUsermethod was called on theUserRepositorywith the expectedUserobject. This ensures that theregisterUsermethod of theUserServiceclass interacts with theUserRepositorycorrectly. - The
verify(userRepository).findUserByEmail(email);method checks if thefindUserByEmailmethod was called on theUserRepositorywith the expected email. This ensures that thegetUserByEmailmethod of theUserServiceclass interacts with theUserRepositorycorrectly.
Additional Scenarios
Scenario: Verifying Method Call Count
In this scenario, we will demonstrate how to verify the number of times a method was called using the verify() method.
@Test
public void testRegisterUserCalledOnce() {
// Given
String name = "John Doe";
String email = "john.doe@example.com";
// When
userService.registerUser(name, email);
// Then
verify(userRepository, times(1)).saveUser(new User(name, email));
}
Scenario: Verifying No Interactions
In this scenario, we will demonstrate how to verify that no interactions occurred with the mock object using the verifyNoInteractions() method.
@Test
public void testNoInteractionsWithRepository() {
// Given
// No interactions expected
// When
// No method calls
// Then
verifyNoInteractions(userRepository);
}
Conclusion
The verify() method in Mockito simplifies the verification of method calls on mock objects for unit testing. By using verify(), you can easily check if certain methods were called with specific arguments, ensuring that the code under test interacts with its dependencies as expected. This step-by-step guide demonstrated how to effectively use the verify() method in your unit tests, covering different scenarios to ensure comprehensive testing of the UserService class.
Related Mockito Methods
Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers
Comments
Post a Comment
Leave Comment