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

服务类中的方法:


@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 做什么。也嘲笑这个?现在我在测试课上有这个:


@Test

public void searchAccountsByPartOfName() {

    service.searchAccounts("test");

    verify(accountDao, times(1)).getAll();

}


BIG阳
浏览 91回答 2
2回答

ABOUTYOU

CollectionUtils.filter是一种基于谓词过滤集合的实用方法。你不需要嘲笑它。你需要做的是模拟accountDao返回一个Collection<Account>. 集合中的帐户实例可以是真实对象或模拟对象。如果它是一个简单的 POJO,我建议创建一个真实 Account 对象的列表。然后,您验证Collection<Account>从列表返回的内容,因为它根据谓词正确过滤掉了 Account 对象。有了这个,你正在测试你的代码/逻辑的症结所在。它可能看起来像这样(免责声明:未编译)@Testpublic void searchAccountsByPartOfName() throws ParseException {&nbsp; &nbsp; Collection<Account> accounts = new ArrayList<>();&nbsp; &nbsp; Account acc1 = new new Account(..); //name having the substring "test"&nbsp; &nbsp; Account acc2 = new new Account(..); //surname equals "test"&nbsp; &nbsp; Account acc3 = new new Account(..);&nbsp; //neither name nor surname has the substring "test"&nbsp; &nbsp; accounts.add(acc1);&nbsp;&nbsp; &nbsp; accounts.add(acc2);&nbsp;&nbsp; &nbsp; accounts.add(acc3);&nbsp; &nbsp; when(accountDao.getAll()).thenReturn(accounts);&nbsp; &nbsp; service.searchAccounts("test");&nbsp; &nbsp; Collection<Account> actual = service.searchAccounts("test");&nbsp; &nbsp; //here assert that the actual is of size 2 and it has the ones that pass the predicate&nbsp; &nbsp; assertEquals(2, actual.size());&nbsp; &nbsp; assertEquals(acc1, actual.get(0));&nbsp; &nbsp; assertEquals(acc2, actual.get(1));}您可能还想编写类似的测试来测试不区分大小写的检查。

九州编程

CollectionUtils.filter()调用包含searchAccounts()方法执行的逻辑,而您希望隔离Collection<Account> accounts = accountDao.getAll();的部分由另一个依赖项执行。&nbsp;所以模拟返回一个特定的帐户列表并断言返回预期的过滤帐户。&nbsp;searchAccounts()accountDao()searchAccounts()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java