模拟间谍可以返回存根值吗?

时间:2019-02-21 14:14:26

标签: java unit-testing testing mockito

我想测试该类,所以它将告诉我用正确的参数调用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;
  }
}

是否有一种方法可以组合模拟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);
}

我想要的结果是错误消息向我展示了与常规间谍一样的预期参数和实际参数之间的差异

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

预期:

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

1 个答案:

答案 0 :(得分:1)

使用间谍时,请使用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;

坦率地说,我不认为您需要在此处进行验证,只需一个布尔断言就足够了,但这取决于您。

相关问题