Mockito: Difference between doThrow() and thenThrow()

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)