我有考试
Document document = spy(new Document());
Whitebox.setInternalState(documentReceiverInteractor, "document", document);
String text= "string";
Whitebox.invokeMethod(documentReceiverInteractor, "saveFields", anyString(), eq(text), anyString(),
anyString(), anyString(), anyString(), anyString());
verify(document).setText(text);
启动后,我收到此错误:
Argument(s) are different! Wanted:
document.setText(
<any string>
);
-> at ru.psbank.msb.dev.business.document.edit.receiver.DocumentReceiverInteractorTest.saveFields(DocumentReceiverInteractorTest.java:98)
Actual invocation has different arguments:
document.setText(
null
);
eq
可以很好地处理基元并且没有任何对象。我该怎么办?
Whitebox.invokeMethod(documentReceiverInteractor, "saveFields",
anyString(), eq(text), anyString(),
anyString(), anyString(), anyString(), anyString());
这句话没有意义。对anyString()
等的召唤是对Mockito的信号,只有在调用when
和verify
时才有意义。它们的返回值是null
,0
,""
或其他虚拟值,以及their side effects are to modify Mockito's internal state;它们不是用于测试的随机或任意值,并且对于Whitebox没有任何特殊行为。
(在引擎盖下,你用setText
的返回值调用eq(text)
,这是null
,并将它与你偶然添加到参数匹配器堆栈的anyString()
的一个调用相匹配。)
而是选择特定值:
Whitebox.invokeMethod(documentReceiverInteractor, "saveFields",
"string 1",
text,
"string 2",
"string 3",
"string 4",
"string 5",
"string 6");
...而不是使用Whitebox,它在Mockito的internal
包org.mockito.internal.util.reflection
中并且是deleted in Mockito 2.2,你应该考虑使方法调用更加可见(如果您的测试在同一个包中则为package-private,否则为public)。毕竟,你的考试是你班上的消费者。如果您选择去那条路线,请考虑添加@VisibleForTesting
或其他一些文档(如/** Visible for testing. */
)。