17

I'm trying to set up a mock for a method that takes an array of Request objects:

client.batchCall(Request[])

I've tried these two variations:

when(clientMock.batchCall(any(Request[].class))).thenReturn(result);
...
verify(clientMock).batchCall(any(Request[].class));

and

when(clientMock.batchCall((Request[])anyObject())).thenReturn(result);
...
verify(clientMock).batchCall((Request[])anyObject());

But I can tell the mocks aren't being invoked.

They both result in the following error:

Argument(s) are different! Wanted:
clientMock.batchCall(
    <any>
);
-> at com.my.pkg.MyUnitTest.call_test(MyUnitTest.java:95)
Actual invocation has different arguments:
clientMock.batchCall(
    {Request id:123},
    {Request id:456}
);

Why does the matcher not match the array? Is there a special matcher I need to use to match an array of objects? The closest thing I can find is AdditionalMatches.aryEq(), but that requires that I specify the exact contents of the array, which I'd rather not do.

3 Answers 3

12

So I quickly put something together to see if I could find your issue, and can't below is my sample code using the any(Class) matcher and it worked. So there is something we are not seeing.

Test case

@RunWith(MockitoJUnitRunner.class)
public class ClientTest
{
    @Test
    public void test()
    {
        Client client = Mockito.mock(Client.class);

        Mockito.when(client.batchCall(Mockito.any(Request[].class))).thenReturn("");

        Request[] requests = {
            new Request(), new Request()};

        Assert.assertEquals("", client.batchCall(requests));
        Mockito.verify(client, Mockito.times(1)).batchCall(Mockito.any(Request[].class));
    }
}

client class

public class Client
{
    public String batchCall(Request[] args)
    {
        return "";
    }
}

Request Class

public class Request
{

}
Sign up to request clarification or add additional context in comments.

1 Comment

Let the question's author to decide if it provides or not an answer to the question
6

Necroposting, but check whether the method you're calling is declared as batchCall(Request[] requests) or batchCall(Request... requests).

If it's the latter, try when(clientMock.batchCall(Mockito.anyVararg())).

1 Comment

Mockito.anyVararg() is deprecated, use (Type) Mockito.any() instead
0

I had the same issue and the reason for me was, that the elements in the arrays had different orders.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.