Mockito Matcher for Integer ...参数

时间:2016-04-25 16:19:50

标签: java unit-testing mocking mockito

此方法中第二个参数的正确Mockito匹配器是什么签名:

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

我尝试了以下匹配器:

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

但是Mockito没有为我创建代理,返回的List为空。

2 个答案:

答案 0 :(得分: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 :(得分:1)

Integer...是定义Integer s数组的语法糖。所以模仿它的正确方法是:

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