gpt4 book ai didi

java - mockito spy 可以返回 stub 值吗?

转载 作者:行者123 更新时间:2023-11-28 21:18:30 24 4
gpt4 key购买 nike

我想测试这个类,所以它会告诉我我用正确的参数调用了 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 spythenReturn?我喜欢 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);
}

结果我想要的是错误消息向我展示参数之间的差异,就像通常的 spy 一样:

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

预期:

  • 我知道我可以只做 stub 然后测试异常,但这不会显示参数的差异

最佳答案

使用Spy 时,请使用doReturn().when() 语法。还要在设置后验证:

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;

坦率地说,我认为您不需要在这里验证,只需一个 boolean 断言就足够了,但这取决于您。

关于java - mockito spy 可以返回 stub 值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com