Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: Difference between doThrow() and thenThrow()

Tags:

mockito

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!")); 
like image 261
Manoj Shrestha Avatar asked Mar 31 '16 20:03

Manoj Shrestha


1 Answers

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.

like image 58
Jeff Bowman Avatar answered Sep 26 '22 04:09

Jeff Bowman