我一直在尝试使用 Mockito 模拟具有可变参数参数的方法:
interface A {
B b(int x, int y, C... c);
}
A a = mock(A.class);
B b = mock(B.class);
when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b);
assertEquals(b, a.b(1, 2));
这不起作用,但是如果我这样做:
when(a.b(anyInt(), anyInt())).thenReturn(b);
assertEquals(b, a.b(1, 2));
这可行,尽管我在 stub 方法时完全省略了可变参数参数。
有什么线索吗?
最佳答案
Mockito 1.8.1 引入 anyVararg() matcher :
when(a.b(anyInt(), anyInt(), Matchers.<String>anyVararg())).thenReturn(b);
另请参阅历史记录:https://code.google.com/archive/p/mockito/issues/62
编辑弃用后的新语法:
when(a.b(anyInt(), anyInt(), ArgumentMatchers.<String>any())).thenReturn(b);
关于java - 如何正确匹配 Mockito 中的可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2631596/