首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >间谍能返回存根值吗?

问间谍能返回存根值吗?
EN

Stack Overflow用户
提问于 2019-02-21 14:14:25
回答 1查看 302关注 0票数 0

我想测试这个类,所以它将向我展示我用右参数调用ws:

代码语言:javascript
复制
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的简单消息。

代码语言:javascript
复制
@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);
}

因此,我想要的是错误消息,它向我展示了预期参数和实际参数之间的差异,就像通常的间谍:

代码语言:javascript
复制
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

预期:

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-21 14:23:11

使用时,请使用doReturn().when()语法。也是在设置之后的verify:

代码语言:javascript
复制
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;

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54809101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档