jeudi 21 février 2019

Can a mockito spy return stub value?

I want to test this class, so it will shows me that I call ws with right params:

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

Is there a way to combine mockito spy and thenReturn? I like how spy will show actual methods calls and not just simple message about 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);
}

What I want as a result is error message showing me the difference between parameters that expected and actual like usual spy's:

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

Expected:

  • I know I can do just stub and then test for exception, but thats will not show the difference in parameters

Aucun commentaire:

Enregistrer un commentaire