Mockito using argument matchers for when call on method with variable number of arguments
java, mockito
Solution
Try the `anyVararg()` matcher. This was introduced in 1.8.1.
Problem
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. ``` 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." 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?