[英]ArgumentCaptor mockito vararg getAllValues
我想驗證一個助手類所做的日志記錄,該類調用帶有一些可變參數的方法。
我正在使用 Mockito (1.10.19) 來模擬實際的記錄器,並驗證模擬的方法是否按預期調用。
我使用 ArgumentCaptor 來驗證參數。
Mockito.verify 驗證調用模擬方法的次數,但是, ArgumentCaptor.getAllValues 返回一個包含所有方法調用的所有參數的單個數組。
這是一個示例代碼:
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 !
}
失敗是:
java.lang.AssertionError:
Expected size:<2> but was:<6> in:
<[0, " : ", ["a", "b"], 1, " : ", ["c", "d"]]>
at TestLogHelper.givenMatrix_whenLogMatrix_thenLogsEachRow(TestLogHelper.java:72)
...
是誤用嗎? 還是 mockito 中的錯誤?
因此,在 5 年后操作問題仍然沒有答案,因為只有解決方法。 這些是:
getAllValues()
提到的 op 之類的getAllValues()
進行驗證。 這是最新 Mockito 3.8.0 文檔中推薦用於可變參數的方法argThat()
可能會更好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.