亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我必須如何用 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 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號