java - 模拟间谍可以返回存根值吗?
问题描述
我想测试这个类,所以它会告诉我我用正确的参数调用 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;
}
}
有没有办法将 mockitospy
和结合起来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
预期的:
- 我知道我可以只做存根然后测试异常,但这不会显示参数的差异
解决方案
使用Spy时,请使用doReturn().when()
语法。同样verify
在设置之后:
MyService spyWs = Mockito.spy(MyWebService.class);
doReturn(true).when(spyWs).sendCustomEmail(any(), any(), any());
MyService::sendEmail(spyWs);
verify(spyWs, once())
.sendCustomEmail(
eq("me@example.com"),
eq("Subject"),
eq("here should be another body and test shou")
);
// assert that sendMail returned true;
坦率地说,我认为您不需要在这里进行验证,只需一个布尔断言就足够了,但这取决于您。
推荐阅读
- java - 避免在junit4中调用CommandLineRunner
- arrays - 什么时候数组 C-contiguous 和 F-contiguous 同时?
- jenkins - Scripted Pipeline 语法中并行内部的顺序阶段
- python - Python中多点下的面积积分
- r - 使用 mutate 将变量名称列表传递给自定义函数
- java - 为什么我的 Apache Ignite 持久存储仍处于锁定状态?
- python - 我无法在 pycharm 中导入 pygame
- elasticsearch - Logstash BeatsParser$InvalidFrameProtocolException
- java - 启动仪表 API 失败:Runner 意外退出
- javascript - 有没有办法使用“in”运算符排除某些元素?