【发布时间】:2019-02-21 14:14:25
【问题描述】:
我想测试这个类,所以它会告诉我我用正确的参数调用 ws:
class MyService {
public static boolean sendEmail(MyWebService ws) {
if (!ws.sendCustomEmail("me@example.com", "Subject", "Body")) {
throw new RuntimeException("can't do this");
}
// ... some more logic which can return false and should be tested
return true;
}
}
有没有办法将 mockito spy 和 thenReturn 结合起来?我喜欢 spy 如何显示实际的方法调用,而不仅仅是关于 assertionFailed 的简单消息。
@Test
void myTest() {
MyService spyWs = Mockito.spy(MyWebService.class);
// code below is not working, but I wonder if there is some library
verify(spyWs, once())
.sendCustomEmail(
eq("me@example.com"),
eq("Subject"),
eq("here should be another body and test shou")
)
.thenReturn(true);
MyService::sendEmail(spyWs);
}
我想要的结果是错误消息向我展示了预期参数和实际参数之间的差异,就像通常的间谍一样:
Test failed:
sendCustomEmail(eq("me@example.com"), eq("Subject"), eq("here should be another body and test should show diff")) was never called
sendCustomEmail(eq("me@example.com"), eq("Subject"), eq("Body")) was called, but not expected
预期:
- 我知道我可以只做存根然后测试异常,但这不会显示参数的差异
【问题讨论】:
标签: java unit-testing testing mockito