模拟访问内部创建的对象验证

Mock Acces inner Created Object Verification

我在 AccountService 中有一个方法,如何验证帐户实例的字段, 例如,我想验证创建的帐户是否具有 USER 角色,

 public ResponseEntity<CreateAccountResponse> createAccount(AccountCreateRequest accountCreateRequest) {

 Account account = new Account();
      account.setId(GenerateUtils.generateTokenWithPrefix(PrefixUUID.ACCOUNT));
      account.setFirstName(accountCreateRequest.getFirstName());
      account.setLastName(accountCreateRequest.getLastName());
      account.setUserName(accountCreateRequest.getEmail());
      //TODO assume that admin user should not create admin user
      account.setRole(AccountRole.USER.toString());
      account.setConfirmed(true);
      account.setLocked(false);
      account.setLoginAttempts(0);
      account.setPassword(DigestUtils.sha256Hex(accountCreateRequest.getPassword()));
  
      Account accountCreated = accountRepository.save(account);

      CreateAccountResponse createAccountResponse = CreateAccountResponse.builder().id(accountCreated.getId()).confirmed(accountCreated.getConfirmed()).firstName(accountCreated.getFirstName()).lastName(accountCreated.getLastName()).locked(accountCreated.getLocked()).loginAttempts(accountCreated.getLoginAttempts()).role(accountCreated.getRole()).userName(accountCreated.getUserName()).build();

      return ResponseEntity.status(HttpStatus.CREATED).body(createAccountResponse);

   }

由于您的 AccountRepository 是模拟的,您可以使用 ArgumentCaptor 捕获调用存储库的 save 方法的参数。

像这样:

@ExtendWith(MockitoExtension.class)
public class SimpleTest {

    @InjectMocks
    private AccountService accountService;

    @Mock
    private AccountRepository accountRepository;

    @Captor
    private ArgumentCaptor<Account> captor;


    @Test
    public void test() {
        when(accountRepository.save(captor.capture())).thenReturn(...);

        Account captorValue = captor.getValue();

        accountService.createAccount(...);

        // verify(accountRepository).save(captor.capture()); // you can also capture here and then captor.getValue()
 

        assertEquals(AccountRole.USER.toString(), captorValue.getRole());
    }
}

你也可以直接在测试方法中创建ArgumentCaptor

ArgumentCaptor<Account> captor = ArgumentCaptor.forClass(Account.class);