Mockito: Difference between doThrow() and thenThrow()

What's the difference between doThrow() and thenThrow()?

Let's say, we want to mock an authentication service to validate the login credentials of a user. What's the difference between the following two lines if we were to mock an exception?

doThrow(new BadCredentialsException("Wrong username/password!")).when(authenticationService).login("user1", "pass1"); 

vs

when(authenticationService.login("user1", "pass1")).thenThrow(new BadCredentialsException("Wrong username/password!")); 

1 Answer

Almost nothing: in simple cases they behave exactly the same. The when syntax reads more like a grammatical sentence in English.

Why "almost"? Note that the when style actually contains a call to authenticationService.login. That's the first expression evaluated in that line, so whatever behavior you have stubbed will happen during the call to when. Most of the time, there's no problem here: the method call has no stubbed behavior, so Mockito only returns a dummy value and the two calls are exactly equivalent. However, this might not be the case if either of the following are true:

  • you're overriding behavior you already stubbed, particularly to run an Answer or throw an Exception
  • you're working with a spy with a non-trivial implementation

In those cases, doThrow will call when(authenticationService) and deactivate all dangerous behavior, whereas when().thenThrow() will invoke the dangerous method and throw off your test.

(Of course, for void methods, you'll also need to use doThrow—the when syntax won't compile without a return value. There's no choice there.)

Thus, doThrow is always a little safer as a rule, but when().thenThrow() is slightly more readable and usually equivalent.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like