Almost nothing: in simple cases, they behave exactly the same. The when syntax reads more like a grammar sentence in English.
Why "almost"? Note that the when style actually contains an authenticationService.login call. This is the first expression evaluated on this line, so any behavior that you missed will occur during the when call. Most of the time there is no problem: the method call has no stunned behavior, so Mockito returns only a dummy value, and the two calls are exactly equivalent. However, this may not be the case if one of the following conditions is true:
- you redefine behavior that you have already killed, in particular to trigger a response or throw an exception.
- you work with a spy with a nontrivial implementation
In these cases, doThrow will call when(authenticationService) and deactivate all the dangerous actions, while when().thenThrow() will call the dangerous method and will reset your test.
(Of course, for void methods, you'll also need to use the doThrow -the when syntax, which will not compile without a return value. There is no choice.)
So doThrow always a little safer, but when().thenThrow() bit readable and usually equivalent.
Jeff bowman
source share