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.
Mocking is usually accomplished by introducing a dynamic proxy on an interface or a subclass of a class. Since a date array is a final class, it is neither an interface nor subclassable, so that takes away the normal approaches for creating a mock.
mockito. Matchers is deprecated, ArgumentMatchers should be used instead.
What are Matchers? Matchers are like regex or wildcards where instead of a specific input (and or output), you specify a range/type of input/output based on which stubs/spies can be rest and calls to stubs can be verified. All the Mockito matchers are a part of 'Mockito' static class.
Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method.
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
{
}
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