31

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?

SQB
  • 3,926
  • 2
  • 28
  • 49
Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

57

Mockito 1.10.5 has introduced this feature.

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 javadoc for details.

sudeep
  • 735
  • 1
  • 9
  • 8
  • Do you happen to know whether this works with subclasses? E.g. String.format(String fromat, Object ... args) and invokation with instances of different types (yeah, I know String is final, it's just an example)? – nachteil Mar 01 '16 at 10:53
  • 1
    @nachteil Yes, `ArgumentCaptor` can capture all subclass instances of `T`. e.g., use `ArgumentCaptor` to capture all types of objects. Please note, a static method like String.format() cannot be mocked or spied upon with Mockito. Please see [this](http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) answer for details. – sudeep Jun 16 '16 at 20:46
  • Is it possible to capture instance variable or local variable in junit ? – avinash kumar Sep 06 '20 at 16:42
3

As of today (7 Nov 2013) it appears to be addressed, but unreleased, with a bit of additional work needed. See the groups thread and issue tracker for details.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251