As part of writing unit tests, many times we might need to verify that the tested method is calling an external dependency method.
Let's consider the following UserServer and UserRepository classes. UserService class is dependent on UserRepository class for fetching a User object with given Id. While writing a unit test for findById() method, it makes sense to verify that findById() method of UserRepository is actually invokes.
@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> {
}
Mockito provides a convenient way of verifying if a particular method was invokes on the mocked class or not. A point to remember here is that the object on which verify is called, must be a mock object created by Mockito. The simplest case to verify that a method of a mocked object is invoked or not is as below.
Mockito.verify(mockObject).methodToBeVerified(method_parameters);
class UserServiceVerifyInvocationTest {
@Test
void simple_mock() {
// Create a mock object using Mockito.
UserRepository mockedUserRepository = Mockito.mock(UserRepository.class);
// Inject mock implementation of UserRepository as dependency to UserService method.
UserService userService = new UserService(mockedUserRepository);
// define expectation from the findById() method of UserRepository mock object
Mockito.doReturn(Optional.of(new User(100L)))
.when(mockedUserRepository)
.findById(100L);
// When the tested method is invoked.
Optional<User> result = userService.findById(100L);
// Then the dummy User object should be returned.
Assertions.assertTrue(result.isPresent());
Assertions.assertEquals(100L, result.get().getId());
// And verify that findById() method of UserRepository was invoked.
Mockito.verify(mockedUserRepository).findById(100L);
}
}
The other options to verify method invocation are as below:
- Verify specific method is called multiple number of times
Mockito.verify(mockObject, Mockito.times(n)).methodToBeVerified(method_parameters);
- Verify no interaction with specific method
Mockito.verify(mockObject, Mockito.never()).methodToBeVerified(method_parameters);
- Verify no interaction with any method of the mock
Mockito.verifyZeroInteractions(mockObject);
- Verify interaction with only specific method and no other interaction
Mockito.verify(mockObject).methodToBeVerified(method_parameters);
Mockito.verifyNoMoreInteractions(mockObject);
0 comments:
Post a Comment