【发布时间】:2021-10-14 10:29:37
【问题描述】:
如何在模拟存储库上捕获操作的值,而不是覆盖返回值。
以这个测试为例
@Mock
AccountRepository accountRepository;
@InjectMocks
AccountService accountService;
@Test
public void remove_staff_updates_roles() {
Account account = new Account("username", "pass");
when(accountRepository.findByUsername(any(String.class))).thenReturn(Optional.of(account));
accountService.updateStaffStatusByUsername("user", false);
// How can I capture the account that is to be saved here?
assertFalse(????.getValue().getRoles().contains(Role.ROLE_STAFF));
}
然后在服务中
public Account updateStaffStatusByUsername(String username, Boolean toState) {
Account account;
if (toState) {
return addRole(username, Role.ROLE_STAFF);
}
return removeRole(username, Role.ROLE_STAFF);
}
Account addRole(String username, Role role) {
Optional<Account> optionalAccount = accountRepository.findByUsername(username);
if (account.isEmpty()) {
throw new CustomException("No account exists with the username: " + username, HttpStatus.NOT_FOUND);
}
Account account = optionalAccount.get();
account.addRole(role);
// I want to intercept this and take the value to evaluate
return accountRepository.save(account);
}
当服务要保存更新后的帐号时,我想验证帐号的状态是否已正确更改。
【问题讨论】:
-
“要在服务保存更新后的帐号时验证帐号的状态是否已正确更改”是什么意思?您是否要检查天气 ROLE_STAFF 是否已添加到 Account 或 accountRepository.save(account) 是否正在工作以更新数据库中的内容?
-
我想基本上测试它要保存到数据库的帐户是否包含/不包含预期的ROLE_STAFF
-
不是 100% 确定我理解您的问题,但您正在寻找的是
ArgumentCaptor吗? -
@CameronMcBroom 请在下面查看我的答案
标签: java spring spring-boot mockito