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
@Mock
annotation creates a mock instance of theUserRepository
interface. This mock instance can be used to simulate the behavior of theUserRepository
in a controlled way.
- The
Injecting Mocks with
@InjectMocks
:- The
@InjectMocks
annotation injects the mockUserRepository
into theUserService
instance to provide a controlled test environment. This allows theUserService
methods to be tested in isolation from the actualUserRepository
implementation.
- The
Verifying Interactions with
any()
:- The
verify(userRepository).saveUser(any(User.class));
method checks if thesaveUser
method was called on theUserRepository
with anyUser
object. This ensures that theregisterUser
method of theUserService
class interacts with theUserRepository
correctly, without caring about the exactUser
object passed. - The
verify(userRepository).findUserByEmail(anyString());
method checks if thefindUserByEmail
method was called on theUserRepository
with anyString
value. This ensures that thegetUserByEmail
method of theUserService
class interacts with theUserRepository
correctly, without caring about the exact email passed.
- The
Stubbing Methods with
any()
:- The
when(userRepository.findUserByEmail(anyString())).thenReturn(user);
method configures the mockUserRepository
to return a specificUser
object when thefindUserByEmail
method is called with anyString
value. This allows thegetUserByEmail
method of theUserService
class 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