Mock Acces内部创建对象验证



我在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方法的参数。

Smth是这样的:

@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);

相关内容

  • 没有找到相关文章

最新更新