doReturn vs thenReturn

6,413 views
Skip to first unread message

Kevin

unread,
Apr 6, 2010, 11:59:10 AM4/6/10
to mockito
It is unclear to me the advantages of preferring thenReturn() over
doReturn() as recommended by the documentation. Within our own
development group, I have advocated doReturn() because it supports all
mocking scenarios where thenReturn() does not (e.g., spy object, void
methods). Can you provide some clear examples where thenReturn() is
superior to the doReturn()? It seems the readability argument is
subjective and falls apart if you take into account that you MUST use
doReturn() in some circumstances. Unfortunately, we have to use
partial mocks (thank you, thank you, thank you) because of legacy code
for some of our unit tests.

Thanks,
-kevin

Kristofer Karlsson

unread,
Apr 6, 2010, 2:30:42 PM4/6/10
to moc...@googlegroups.com
I would say that the advantages are:
* Compile time type safety of return type.
* Logical flow of specifying the matching before the return value.

Disadvantages are of course, as you say:
* Doesn't work for all cases (void, exception throwing mocks)
* Relies on ordering of method calls, in order for the when() call to catch the correct mock method call. This makes inlining other mock operations in the stubbing hard or impossible to do.

I think when().thenReturn() is preferred simply for the readability, and the type safety.
I've personally found the type safety to be of great convenience when using a good IDE such as IntelliJ.


--
You received this message because you are subscribed to the Google Groups "mockito" group.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.


szczepiq

unread,
Apr 14, 2010, 10:59:55 AM4/14/10
to moc...@googlegroups.com
Hey,


>I think when().thenReturn() is preferred simply for the readability, and the type safety.

Exactly. Personally, I'm not so keen compile-time type safety because runtime type safety is good enough for me ;) It's the readability that counts for me (although I totally agree that it is subjective).


>as recommended by the documentation.

I'll try to be more explicit & relaxed in the documentation so that it is clear why we prefer one way over the other and that you are welcome to choose the style you prefer.

Cheers,
Szczepan
Reply all
Reply to author
Forward
0 new messages