Java – match an array of objects using mockito
•
Java
I'm trying to set up a simulation for a method that requires an array of request objects:
client.batchCall(Request[])
I've tried these two variants:
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 that ridicule was not quoted
They all cause the following errors:
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 that I need to use to match an array of objects? The closest I found was additive matches Aryeq(), but this requires me to specify the exact contents of the array. I'd rather not do it
Solution
So I quickly put things together to see if I can find your problem. Here is the sample code I use any (class) matcher and how it works So there are some things we don't see
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
{
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
