2 回答

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));
}
您可能還想編寫類似的測試來測試不區分大小寫的檢查。

TA貢獻1785條經驗 獲得超4個贊
CollectionUtils.filter()
調用包含searchAccounts()
方法執行的邏輯,而您希望隔離Collection<Account> accounts = accountDao.getAll();
的部分由另一個依賴項執行。 所以模擬返回一個特定的帳戶列表并斷言返回預期的過濾帳戶。 searchAccounts()
accountDao()
searchAccounts()
添加回答
舉報