可以使用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;
  }
}

有没有办法将Mockito spythenReturn组合?我喜欢spy将如何显示实际方法调用,而不仅仅是关于断言的简单消息。

@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;

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

相关内容

  • 没有找到相关文章

最新更新