thenReturn and doReturn
are used for setting up stubs and are provided by the Mockito framework. They are generally used along with when clause as --> when-thenReturn
and doReturn-when
. when-thenReturn
is used in most cases due to better readability.
Following are the differences between thenReturn
and doReturn
:
* Type safety : doReturn
takes Object parameter, unlike thenReturn
. Hence there is no type check in doReturn
at compile time. In the case of thenReturn
, whenever the type mismatches during runtime, the WrongTypeOfReturnValue
exception is raised. This is why when-thenReturn
is a better option whenever we know the type.
* No side-effect : Since doReturn
does not have type safety, there are no side effects when it is being used. Whenever thenReturn
is used, if the type mismatch occurs, an exception is thrown which might result in the abortion of test cases.