I dug a bit more than this, and the answer to why both syntaxes exist can be found in the old release notes, and a referenced mailing list discussion.
To start with, doReturn()
was added in version 1.5 (26/07/2008), while when()
was added in version 1.6 (21/10/2008). when()
was implemented to replace the old stub()
method and doReturn()
to replace stubVoid()
. Basically this is a design deicision by the creator of Mockito (cited from the mailing list 29/06/2008):
I never liked stubVoid() syntax but that was the best I could think
of. The stubbing syntax I'd implement now if I did mockito again:
//regular stubbing:
when(mock.getStuff()).thenReturn("foo");
when(mock.getStuff()).thenThrow(new RuntimeException());
//for void methods and some corner cases:
doReturn("foo").when(mock).getStuff();
doThrow(new RuntimeException()).when(mock).someMethod();
//for stubbing consecutively:
when(mock.getStuff()).thenReturn("foo").thenThrow(new RuntimeException());
doThrow(new RuntimeException()).thenReturn("foo").when(mock).someMethod();
I proposed this syntax couple of weeks ago but received only single
feedback saying that it's rather cosmetic (which is true...). Hence I
decided not to change the API.
And as already pointed out by Bewusstsein in the comments, when()
provides type safety. If we have a method String doSomething()
both below blocks will compile. The latter will however throw an exception during runtime.
Mockito.doReturn("String").when(mock).doSomething();
Mockito.doReturn(1).when(mock).doSomething();
So, to conclude, it was a design decision to introduce both ways of mocking. when()
was imlemented as the prefered way of mocking, due to its type safety and its fluent reading. doReturn()
was implemented to allow for mocking of void
methods and other corner cases.