简体   繁体   English

Mockito 嘲笑未被调用 - ArgumentCaptor 被忽略

[英]Mockito mocks not being called - ArgumentCaptor being ignored

I want to test the following code, on a UserServiceImplV1 class:我想在UserServiceImplV1类上测试以下代码:

    @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.提前致谢。

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.所以在这一点上,模拟还没有被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM