Issue
While doing unit tests on each method of the service layer, I have encountered the below scenario, that I couldn’t figure out how to test:
public class UserServiceImpl{
@Autowired
UserRepository userRepository;
public void abc(){
xyz(obj);
}
private void xyz(){
userRepository.save(obj);
}
}
What I want to test is the abc()
method. Within that method, it invokes xyz()
which is a PRIVATE method that uses the userRepository
dependency. So, when I create a unit test for the abc()
method, do I need to be concerned about the xyz()
method since it is using a dependency? And if yes, what are the steps that I need to follow?
Solution
Since this is a void method, what you want to do is verify that the save
method of the dependency has been called exactly once with the parameter obj
. You could do this by using something like Mockito
. Your unit test would look something like this:
@Mock
private UserRepository mockUserRepository;
@InjectMocks
private UserServiceImpl sut;
@Test
public void abc_savesObject() {
// Arrange
...
// Act
sut.abc();
// Assert
verify(mockUserRepository,times(1)).save(obj);
}
Some useful links:
- https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#4
- https://www.baeldung.com/mockito-verify
Answered By - Ivan Agrenich
Answer Checked By - Marilyn (JavaFixing Volunteer)