【问题标题】:How to get the value of a mock service with Mockito and Spring如何使用 Mockito 和 Spring 获得模拟服务的价值
【发布时间】: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


【解决方案1】:

在这里,您传递 Account(可选)类对象 account 以响应模拟服务,并且同一对象正在更新并保存在数据库中,您需要验证该对象中的值。

 assertFalse(account.getRoles().contains(Role.ROLE_STAFF)); //or vice-verse

【讨论】:

    【解决方案2】:

    在我看来ArgumentCaptor 是您所需要的。请尝试以下操作:

    @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);
    
        ArgumentCaptor<Account> accountCaptor = ArgumentCaptor.forClass(Account.class);
        verify(accountRepository).save(accountCaptor.capture());
        assertFalse(accountCaptor.getValue().getRoles().contains(Role.ROLE_STAFF));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2021-07-12
      相关资源
      最近更新 更多