Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture variable parameters with Mockito?

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?

like image 584
Freewind Avatar asked Nov 08 '13 04:11

Freewind


People also ask

What is the use of ArgumentCaptor in mockito?

Mockito ArgumentCaptor is used to capture arguments for mocked methods. ArgumentCaptor is used with Mockito verify() methods to get the arguments passed when any method is called. This way, we can provide additional JUnit assertions for our tests.

Which annotation is used to capture the values in the method?

The @Captor annotation is used to create an ArgumentCaptor instance which is used to capture method argument values for further assertions.

What does argument capture do?

ArgumentCaptor allows us to capture an argument passed to a method to inspect it. This is especially useful when we can't access the argument outside of the method we'd like to test.

What is stubbing in mockito?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.


2 Answers

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.

like image 151
sudeep Avatar answered Sep 19 '22 18:09

sudeep


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.

like image 39
Jeff Bowman Avatar answered Sep 18 '22 18:09

Jeff Bowman