30

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:

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.

How to fix it?

4

2 回答 2

52

Mockito 1.10.5 引入了这个特性。

对于问题中的代码示例,这是捕获可变参数的一种方法:

    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());

有关详细信息,请参阅ArgumentCaptor javadoc

于 2015-02-11T22:39:40.400 回答
3

截至今天(2013 年 11 月 7 日),它似乎已得到解决,但尚未发布,还需要一些额外的工作。有关详细信息,请参阅组线程问题跟踪器

于 2013-11-08T05:18:10.693 回答