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!"));
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With