How to verify value of an argument passed to a mocked method?
While writing unit tests, we might need to verify the parameters passed to a dependency method, from the method being tested. Mockito provides an easy way to achieve this.
Mockito provides ArgumentMatcher class that can be used to verify arguments passed to a mocked method.
We will be using the UserService and UserRepository class in this example. UserService is the class that is being unit tested and UserRepository is a dependency class that has to be mocked.
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* Save a user in database
*
* @param id
* @return
*/
public Optional<User> findById(Long id) {
if (id == null) {
throw new RuntimeException("Id is required");
}
return userRepository.findById(id);
}
}
public interface UserRepository extends JpaRepository<User, Long> {
}
The ArgumentMatcher, is a functional interface, that we can pass as the part of the `Mockito.verify()` calls to access parameters passed to a mock and perform checks over it.
Now, let's see our example test class, where we are verifying that the argument passed to the findById() method of UserRepository is equal to 100. In this example, we will use `Mockito.argThat()` method and pass it a custom implementation of an ArgumentMatcher to verify parameter value.
/**
* In this example we will use ArgumentMatchers to verify the values passed to a mock method as parameters.
*/
class UserServiceArgumentMatcherTest {
@Test
void verify_argument() {
// Create a mock object for dependency class
UserRepository mockUserRepository = Mockito.mock(UserRepository.class);
// Add mocked dependency to the class object being tested
UserService userService = new UserService(mockUserRepository);
// Use when-thenReturn format to specify return value for invoked method on mock
Mockito.when(mockUserRepository.findById(100L)).thenReturn(Optional.of(new User(100L)));
// Invoke the method to be tested
userService.findById(100L);
// Verify that we have called findById() method of UserRepository with correct arguments
Mockito.verify(mockUserRepository).findById(Mockito.argThat((Long id) -> id == 100L));
}
}
0 comments:
Post a Comment