Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito using argument matchers for when call on method with variable number of arguments

Tags:

java

mockito

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?

like image 867
Andrew Avatar asked Apr 18 '12 17:04

Andrew


People also ask

How do you use argument matchers in Mockito?

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.

What can I use instead of Mockito matchers?

mockito. Matchers is deprecated, ArgumentMatchers should be used instead.

Can the Mockito Matcher methods be used as return values?

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.


1 Answers

Try the anyVararg() matcher. This was introduced in 1.8.1.

like image 55
user1329572 Avatar answered Sep 18 '22 12:09

user1329572