简体   繁体   English

ArgumentCaptor mockito vararg getAllValues

[英]ArgumentCaptor mockito vararg getAllValues

I want to validate the logging made by a helper class, which calls a method with some varargs.我想验证一个助手类所做的日志记录,该类调用带有一些可变参数的方法。

I am using Mockito (1.10.19) to mock the actual logger, and to verify the mocked method is called as expected.我正在使用 Mockito (1.10.19) 来模拟实际的记录器,并验证模拟的方法是否按预期调用。

I use an ArgumentCaptor to validate the arguments.我使用 ArgumentCaptor 来验证参数。

The Mockito.verify validates the number of times the mocked method is called, however, the ArgumentCaptor.getAllValues is returning a single array with all the parameters of all the method calls. Mockito.verify 验证调用模拟方法的次数,但是, ArgumentCaptor.getAllValues 返回一个包含所有方法调用的所有参数的单个数组。

Here is a sample code:这是一个示例代码:

interface Logger
{
    void info(Object... params);
}

@Mock
Logger logger;

public void logMatrix(String[][] matrix)
{
    for (int column = 0; column < matrix.length; column++)
    {
        logger.info(column, " : ", matrix[column]);
    }
}

@Test
public void givenMatrix_whenLogMatrix_thenLogsEachRow() throws Exception
{
    String[][] matrix = {
        {"a", "b"},
        {"c", "d"}
    };

    ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);

    logMatrix(matrix);

    // verify the mocked method is called twice
    Mockito.verify(logger, times(2)).info(captor.capture());

    // verify the contents of the calls: expecting two arrays, one for each call 
    assertThat(captor.getAllValues()).hasSize(2);
    // fails !
}

The failure is:失败是:

java.lang.AssertionError: 
   Expected size:<2> but was:<6> in:
      <[0, " : ", ["a", "b"], 1, " : ", ["c", "d"]]>
   at TestLogHelper.givenMatrix_whenLogMatrix_thenLogsEachRow(TestLogHelper.java:72)
...

Is it a misuse?是误用吗? or a bug in mockito ?还是 mockito 中的错误?

So after 5 years ops question is still unanswered because there are only workarounds present.因此,在 5 年后操作问题仍然没有答案,因为只有解决方法。 These are:这些是:

  • If you only have single invocation of tested method you can still use captors like op mentioned using getAllValues() for verification.如果您只有一次调用测试方法,您仍然可以使用像使用getAllValues()提到的 op 之类的getAllValues()进行验证。 This is the method recommended for varargs in documentation for latest Mockito 3.8.0这是最新 Mockito 3.8.0 文档中推荐用于可变参数的方法
  • If you have multiple invocations you will not be able to tell which argument was passed in which invocation, you will just have them in one list.如果您有多个调用,您将无法分辨在哪个调用中传递了哪个参数,您只会将它们放在一个列表中。 You will still be able to verify number of invocations.您仍然可以验证调用次数。 Yet, you might be better using argThat() in this scenario但是,在这种情况下使用argThat()可能会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM