使用 Mockito 匹配对象数组

新手上路,请多包涵

我正在尝试为采用 Request 对象数组的方法设置模拟:

 client.batchCall(Request[])

我试过这两种变体:

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

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

但我可以告诉模拟没有被调用。

它们都会导致以下错误:

 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}
);

为什么匹配器不匹配数组?是否需要使用特殊的匹配器来匹配对象数组?我能找到的最接近的东西是 AdditionalMatches.aryEq(),但这需要我指定数组的确切内容,我宁愿不这样做。

原文由 Vysarat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
1 个回答

因此,我很快将一些东西放在一起,看看是否可以找到您的问题,但下面是我使用 any(Class) 匹配器的示例代码,它可以正常工作。所以有些东西我们没有看到。

测试用例

@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));
    }
}

客户类

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

请求类

public class Request
{

}

原文由 ndrone 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题