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

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

使用 any() 或 anyList() 時,使用 ArrayList/List 參數清除方法失敗

使用 any() 或 anyList() 時,使用 ArrayList/List 參數清除方法失敗

慕桂英546537 2022-12-28 10:18:25
我有一個java類。class Blah{        public Blah(){        }        public String testMe(List<String> s){            return new String("hello "+s.get(0));        }        public String testMeString(String s){            return new String("hello "+s);        }    }我無法嘗試成功地存根和測試 testMe 方法。請注意,我只是想了解 java 中的模擬。例如我試過:    @Test    public void testTestMe(){        Blah blah = spy(new Blah());        ArrayList<String> l = new ArrayList<String>();        l.add("oopsie");        when(blah.testMe(Matchers.any())).thenReturn("intercepted");        assertEquals("intercepted",blah.testMe(l));這將返回 NullPointerException。我也嘗試過任何(List.class),任何(ArrayList.class)。我也嘗試過使用anyList(),但這給了我一個 IndexOutOfBounds 錯誤。我究竟做錯了什么?有趣的是,我的testMeString作品很好。如果我做@Test    public void testTestMeString(){        Blah blah = spy(new Blah());        when(blah.testMeString(any())).thenReturn("intercepted");        assertEquals("intercepted",blah.testMeString("lala"));}測試通過 any() 和 any(String.class)。
查看完整描述

3 回答

?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

通過將此語句blah.testMe()包含在 中when(),它會調用真正的方法:


when(blah.testMe(Matchers.any())).thenReturn("intercepted");

為避免這種情況,您應該使用doReturn(...).when(...).methodToInvoke()模式。


doReturn("intercepted").when(blah).testMe(Matchers.any()));

您注意到使用此語法:blah.testMe()語句未在任何地方指定。所以那不叫。


除了這個問題,我認為你不需要任何間諜來測試這個方法。

間諜是一種非常特殊的模擬工具,僅當您別無選擇時才使用它:您需要模擬被測對象,這是一種不好的做法,并且您無法重構實際代碼。


但在這里你可以這樣做:


@Test

public void testTestMe(){

    Blah blah = new Blah();

    ArrayList<String> l = new ArrayList<String>();

    l.add("oopsie");

    assertEquals("hello oopsie",blah.testMe(l));

 }


查看完整回答
反對 回復 2022-12-28
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

您應該重新考慮 usingspy等mock。當您有外部系統、休息 web 服務、您不想在單元測試期間調用的數據庫時,應該使用這些設施。在像這樣的簡單場景中,只需創建一些測試輸入并檢查輸出。


@Test public void testTestMeString(){

 //given

  List<String> list = Arrays.asList("aaa");

 //when

 String result = blah.testMe(list);

 //then

 assertEquals(result, "hello aaa");

 }

當您有興趣時,given, when, then請檢查 BDD。


查看完整回答
反對 回復 2022-12-28
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

您的 NullPointerException 在存根期間被拋出,而不是在測試期間。

這是因為Matchers.any()實際上返回null,所以如果您在調用真正的方法時使用它,您將null作為參數傳遞。testMeString恰好有效,因為null + s不會導致 NullPointerException("null"改為使用字符串)。

代替:

when(blah.testMe(any())).thenReturn("intercepted");

你需要使用

doReturn("intercepted").when(blah).testMe(any());

這被記錄為(雖然承認不是非常清楚)作為間諜真實物體的重要陷阱!在 Mockito 文檔中。


查看完整回答
反對 回復 2022-12-28
  • 3 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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