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?
Mockito uses equal() as a legacy method for verification and matching of argument values. In some cases, we need more flexibility during the verification of argument values, so we should use argument matchers instead of equal() method. The ArgumentMatchers class is available in org. mockito package.
mockito. Matchers is deprecated, ArgumentMatchers should be used instead.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
Try the anyVararg()
matcher. This was introduced in 1.8.1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With