2016-04-25 81 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