doReturn()
is similar to stubbing a method and returns the expected value. But this is used only when when(mock).thenReturn(return)
cannot be used.
when-thenReturn
is more readable than doReturn()
, also doReturn()
is not type safe. thenReturn
checks method return types and raises compilation error if an unsafe type is passed.
Here is the syntax for using the doReturn()
test:
doReturn(value).when(mock).method(argument); public class DoReturnTest { @Mock StockBroker broker; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void doReturn_is_not_type_safe() throws Exception { //get Qoute returns double when(broker.getQoute(isA(Stock.class))).thenReturn(5.00); //returning string for getQoute…although return type is double doReturn("string").when(broker).getQoute(isA(Stock.class)); broker.getQoute(new Stock("A1", 40.00)); } }
The following screenshot shows...