Reputation: 1072
I want to test the following code, on a UserServiceImplV1
class:
@Override
public void updateUserPassword(VerificationCodeDTO code, String newPassword) {
if(verificationCodeService.isValid(code)) {
UserDTOV1 user = userService.findByEmail(code.getEmail());
user.setPassword(newPassword);
userService.save(user);
verificationCodeService.delete(code.getEmail());
} else {
throw new ValidationException("Código de usuário inválido");
}
}
So I wrote the following test:
@Test
public void updatesUserPasswordAndDeletesToken() {
UserDTOV1 userDTO = new UserDTOV1("John", "a@mail.com", "123", UserType.PESSOAFISICA, "oldPassword");
VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO("abcd", userDTO.getEmail());
when(verificationCodeService.isValid(any())).thenReturn(Boolean.TRUE);
when(userService.findByEmail("a@mail.com")).thenReturn(userDTO);
when(userService.save(any(UserDTOV1.class))).thenAnswer(invocation -> invocation.getArgument(0));
ArgumentCaptor<UserDTOV1> captor = ArgumentCaptor.forClass(UserDTOV1.class);
verify(userService, times(1)).save(captor.capture());
UserDTOV1 actual = captor.getValue();
authService.updateUserPassword(verificationCodeDTO, "newPassword");
Assert.assertEquals("newPassword", actual.getPassword());
verify(verificationCodeService, times(1)).delete(anyString());
}
And I get the following error:
Wanted but not invoked:
userService.save(<Capturing argument>);
-> at (...).updatesUserPasswordAndDeletesToken(AuthServiceImplV1Test.java:45)
Actually, there were zero interactions with this mock.
I've tried capturing arguments in a lot of ways, like
verify(userService, times(1)).save(argThat(argument -> argument.getPassword().equals("newPasword")));
But the error is the same, almost as if my mocks weren't being applied. I'm creating them, though, and all the other tests in this file work:
@RunWith(MockitoJUnitRunner.class)
public class AuthServiceImplV1Test {
@Mock
private UserServiceImplV1 userService;
@Mock
private VerificationCodeServiceImplV1 verificationCodeService;
@InjectMocks
private AuthServiceImplV1 authService;
Thanks in advance.
Upvotes: 0
Views: 515
Reputation: 692181
You're verifying that the mock has been called before calling the method under test. So at that point, the mock hasn't been called yet.
Upvotes: 1