Java 如何使用 Mockito 捕获可变参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19851542/
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
How to capture variable parameters with Mockito?
提问by Freewind
There is a method which has variable parameters:
有一种具有可变参数的方法:
class A {
public void setNames(String... names) {}
}
Now I want to mock it with mockito
, and capture the names passed to it. But I can't find a way to capture any number of names passed, I can only get them like this:
现在我想用 来模拟它mockito
,并捕获传递给它的名称。但是我找不到一种方法来捕获传递的任意数量的名称,我只能像这样获取它们:
ArgumentCaptor<String> captor1 = ArgumentCaptor.fromClass(String.class);
ArgumentCaptor<String> captor2 = ArgumentCaptor.fromClass(String.class);
A mock = Mockito.mock(A.class);
mock.setNames("Jeff", "Mike");
Mockito.verity(mock).setNames(captor1.capture(), captor2.capture());
String name1 = captor1.getValue(); // Jeff
String name2 = captor2.getValue(); // Mike
If I pass three names, it won't work, and I have to define a captor3
to capture the 3rd name.
如果我传递三个名称,它将不起作用,我必须定义一个captor3
来捕获第三个名称。
How to fix it?
如何解决?
回答by Jeff Bowman
As of today (7 Nov 2013) it appears to be addressed, but unreleased, with a bit of additional work needed. See the groups threadand issue trackerfor details.
截至今天(2013 年 11 月 7 日),它似乎已得到解决,但尚未发布,需要做一些额外的工作。有关详细信息,请参阅组线程和问题跟踪器。
回答by sudeep
Mockito 1.10.5 has introduced this feature.
Mockito 1.10.5 引入了这个功能。
For the code sample in the question, here is one way to capture the varargs:
对于问题中的代码示例,这是捕获可变参数的一种方法:
ArgumentCaptor<String> varArgs = ArgumentCaptor.forClass(String.class);
A mock = Mockito.mock(A.class);
mock.setNames("Jeff", "Mike", "John");
Mockito.verify(mock).setNames(varArgs.capture());
//Results may be validated thus:
List<String> expected = Arrays.asList("Jeff", "Mike", "John");
assertEquals(expected, varArgs.getAllValues());
Please see the ArgumentCaptor javadocfor details.
有关详细信息,请参阅ArgumentCaptor javadoc。