🎓 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 any() method in Mockito is used to match any value passed to a method. This is particularly useful when you want to verify interactions or stub methods without caring about the exact values of the arguments. This tutorial will demonstrate how to use the any() method in Mockito to handle method arguments.
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 any() method in Mockito to verify and stub methods without caring about the exact argument values.
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(any(User.class));
}
@Test
public void testGetUserByEmail() {
// Given
User user = new User("Jane Doe", "jane.doe@example.com");
when(userRepository.findUserByEmail(anyString())).thenReturn(user);
// When
User result = userService.getUserByEmail("random.email@example.com");
// Then
assertNotNull(result);
assertEquals("Jane Doe", result.getName());
assertEquals("jane.doe@example.com", result.getEmail());
verify(userRepository).findUserByEmail(anyString());
}
}
Explanation
Creating Mocks with
@Mock:- The
@Mockannotation creates a mock instance of theUserRepositoryinterface. This mock instance can be used to simulate the behavior of theUserRepositoryin a controlled way.
- The
Injecting Mocks with
@InjectMocks:- The
@InjectMocksannotation injects the mockUserRepositoryinto theUserServiceinstance to provide a controlled test environment. This allows theUserServicemethods to be tested in isolation from the actualUserRepositoryimplementation.
- The
Verifying Interactions with
any():- The
verify(userRepository).saveUser(any(User.class));method checks if thesaveUsermethod was called on theUserRepositorywith anyUserobject. This ensures that theregisterUsermethod of theUserServiceclass interacts with theUserRepositorycorrectly, without caring about the exactUserobject passed. - The
verify(userRepository).findUserByEmail(anyString());method checks if thefindUserByEmailmethod was called on theUserRepositorywith anyStringvalue. This ensures that thegetUserByEmailmethod of theUserServiceclass interacts with theUserRepositorycorrectly, without caring about the exact email passed.
- The
Stubbing Methods with
any():- The
when(userRepository.findUserByEmail(anyString())).thenReturn(user);method configures the mockUserRepositoryto return a specificUserobject when thefindUserByEmailmethod is called with anyStringvalue. This allows thegetUserByEmailmethod of theUserServiceclass to be tested with controlled behavior from theUserRepository.
- The
Additional Scenarios
Scenario: Verifying Method Called with Any Argument
In this scenario, we will demonstrate how to verify that a method was called with any argument of a specific type.
@Test
public void testSaveUserWithAnyUser() {
// Given
User user = new User("John Doe", "john.doe@example.com");
// When
userService.registerUser(user.getName(), user.getEmail());
// Then
verify(userRepository).saveUser(any(User.class));
}
Scenario: Stubbing Method with Any Argument
In this scenario, we will demonstrate how to stub a method with any argument of a specific type.
@Test
public void testFindUserByEmailWithAnyString() {
// Given
User user = new User("Jane Doe", "jane.doe@example.com");
when(userRepository.findUserByEmail(anyString())).thenReturn(user);
// When
User result = userService.getUserByEmail("random.email@example.com");
// Then
assertNotNull(result);
assertEquals("Jane Doe", result.getName());
assertEquals("jane.doe@example.com", result.getEmail());
verify(userRepository).findUserByEmail(anyString());
}
Conclusion
The any() method in Mockito simplifies the verification and stubbing of method calls on mock objects for unit testing. By using any(), you can handle method arguments flexibly, ensuring that the code under test interacts with its dependencies as expected without caring about the exact values. This step-by-step guide demonstrated how to effectively use the any() 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