java Mockito 使用参数匹配器来调用具有可变数量参数的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10214311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito using argument matchers for when call on method with variable number of arguments
提问by Andrew
I am attempting to use argument matchers inside a when call to a method that has a variable number of arguments (the ...
thing in Java) without success. My code is below and I'll also list all of the lines I tried using to make this work.
我试图在调用具有可变数量参数(...
Java 中的东西)的方法的 when 调用中使用参数匹配器,但没有成功。我的代码在下面,我还将列出我尝试使用的所有行来完成这项工作。
import static org.mockito.Mockito.*;
public class MethodTest {
public String tripleDot(String... args) {
String sum = "";
for (String i : args) {
sum += i;
}
System.out.println(sum);
return sum;
}
public static void main(String[] args) {
try{
MethodTest mt = mock(MethodTest.class);
when(mt.tripleDot((String[])anyObject())).thenReturn("Hello world!");
System.out.println(mt.tripleDot(new String[]{"1","2"}));
}
catch (Exception e) {
System.out.println(e.getClass().toString() + ": " + e.getMessage());
}
}
}
If print statement is:
如果打印语句是:
System.out.println(mt.tripleDot(new String[]{"1"}));
or
或者
System.out.println(mt.tripleDot("1"));
It will print "Hello world."
它将打印“Hello world”。
But if the print statement is:
但是如果打印语句是:
System.out.println(mt.tripleDot(new String[]{"1","2"}));
or
或者
System.out.println(mt.tripleDot("1","2"));
It will print "null".
它将打印“空”。
I've also tried doing variations in the when call, such as anyObject()
or anyString()
but to no avail. I'm not sure if Mockito can handle using argument matchers in regard to method calls that include a variable number of arguments. Is it even possible? If so, what should I be doing to make this work?
我也试过在 when 调用中做一些变化,比如anyObject()
oranyString()
但无济于事。我不确定 Mockito 是否可以处理使用参数匹配器来处理包含可变数量参数的方法调用。甚至有可能吗?如果是这样,我应该怎么做才能使这项工作发挥作用?
回答by user1329572
Try the anyVararg()
matcher. This was introduced in 1.8.1.
尝试anyVararg()
匹配器。这是在 1.8.1 中引入的。
回答by John B
Try Mockito.anyVararg()
. It should work.
试试Mockito.anyVararg()
。它应该工作。