[英]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:
这些是:
getAllValues()
for verification.getAllValues()
提到的 op 之类的getAllValues()
进行验证。 This is the method recommended for varargs in documentation for latest Mockito 3.8.0argThat()
in this scenarioargThat()
可能会更好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.