Java 使用 Mockito 匹配对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25495912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matching an array of Objects using Mockito
提问by Vysarat
I'm trying to set up a mock for a method that takes an array of Request objects:
我正在尝试为采用 Request 对象数组的方法设置模拟:
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.
为什么匹配器不匹配数组?是否需要使用特殊的匹配器来匹配对象数组?我能找到的最接近的东西是 AdditionalMatches.aryEq(),但这要求我指定数组的确切内容,而我不想这样做。
回答by ndrone
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.
所以我很快把一些东西放在一起,看看我是否能找到你的问题,下面是我使用 any(Class) 匹配器的示例代码,它起作用了。所以有些东西我们没有看到。
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
{
}
回答by mrec
Necroposting, but check whether the method you're calling is declared as batchCall(Request[] requests)
or batchCall(Request... requests)
.
Necroposting,但请检查您正在调用的方法是否声明为batchCall(Request[] requests)
or batchCall(Request... requests)
。
If it's the latter, try when(clientMock.batchCall(Mockito.anyVararg()))
.
如果是后者,请尝试when(clientMock.batchCall(Mockito.anyVararg()))
。