2016-04-25 36 views
2

什麼是正確匹配的Mockito在此方法簽名的第二個參數:匹配器的Mockito整數...參數

List<Something> findSomething(Object o, Integer... ids); 

我嘗試了以下的匹配:

when(findSomething(any(), anyInt())).thenReturn(listOfSomething); 
when(findSomething(any(), any())).thenReturn(listOfSomething); 

,但被的Mockito沒有創造代理我,退回List是空的。

回答

4

使用anyVararg()這樣的:

Application application = mock(Application.class); 
List<Application> aps = Collections.singletonList(new Application()); 

when(application.findSomething(any(), anyVararg())).thenReturn(aps); 

System.out.println(application.findSomething("foo").size()); 
System.out.println(application.findSomething("bar", 17).size()); 
System.out.println(application.findSomething(new Object(), 17, 18, 19, 20).size()); 

輸出:

1 
1 
1 
1

Integer...是定義Integer的數組頂部的語法糖。所以正確的方式來嘲笑這將是:

when(findSomething(any(), any(Integer[].class))).thenReturn(listOfSomething); 
+0

這導致一個編譯器錯誤: 的方法SomethingService類型中的findSomething(Object,Integer ...)不適用於參數(Object,Matcher ) – w33z33