为了账号安全,请及时绑定邮箱和手机立即绑定

我必须如何用 mockito 测试这个方法?

我必须如何用 mockito 测试这个方法?

BIG阳 2022-10-26 16:42:27
服务类中的方法:@Override@Transactional(readOnly = true)public Collection<Account> searchAccounts(String partOfName) {    Collection<Account> accounts = accountDao.getAll();    CollectionUtils.filter(accounts, account ->            account.getName().toLowerCase().contains(partOfName.toLowerCase()) ||                    account.getSurname().toLowerCase().equalsIgnoreCase(partOfName.toLowerCase()));    return accounts;}我不明白我必须对 CollectionUtils.filter 做什么。也嘲笑这个?现在我在测试课上有这个:@Testpublic void searchAccountsByPartOfName() {    service.searchAccounts("test");    verify(accountDao, times(1)).getAll();}
查看完整描述

2 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

CollectionUtils.filter是一种基于谓词过滤集合的实用方法。你不需要嘲笑它。


你需要做的是模拟accountDao返回一个Collection<Account>. 集合中的帐户实例可以是真实对象或模拟对象。如果它是一个简单的 POJO,我建议创建一个真实 Account 对象的列表。


然后,您验证Collection<Account>从列表返回的内容,因为它根据谓词正确过滤掉了 Account 对象。


有了这个,你正在测试你的代码/逻辑的症结所在。


它可能看起来像这样(免责声明:未编译)


@Test

public void searchAccountsByPartOfName() throws ParseException {

    Collection<Account> accounts = new ArrayList<>();

    Account acc1 = new new Account(..); //name having the substring "test"

    Account acc2 = new new Account(..); //surname equals "test"

    Account acc3 = new new Account(..);  //neither name nor surname has the substring "test"

    accounts.add(acc1); 

    accounts.add(acc2); 

    accounts.add(acc3);


    when(accountDao.getAll()).thenReturn(accounts);


    service.searchAccounts("test");


    Collection<Account> actual = service.searchAccounts("test");


    //here assert that the actual is of size 2 and it has the ones that pass the predicate

    assertEquals(2, actual.size());

    assertEquals(acc1, actual.get(0));

    assertEquals(acc2, actual.get(1));

}

您可能还想编写类似的测试来测试不区分大小写的检查。


查看完整回答
反对 回复 2022-10-26
?
九州编程

TA贡献1785条经验 获得超4个赞

CollectionUtils.filter()调用包含searchAccounts()方法执行的逻辑,而您希望隔离Collection<Account> accounts = accountDao.getAll();的部分由另一个依赖项执行。 所以模拟返回一个特定的帐户列表并断言返回预期的过滤帐户。 searchAccounts()
accountDao()searchAccounts()

查看完整回答
反对 回复 2022-10-26
  • 2 回答
  • 0 关注
  • 85 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信