I'm trying to use the Mockito deep stubbing feature with the doReturn
method.
When I use the when
method as in the deep stubbing example it works fine:
Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
when(mock.getBar().getName()).thenReturn("deep");
But when I try then same thing with doReturn
I get a WrongTypeOfReturnValue
:
doReturn("deep").when(mock).getBar().getName();
I have also tried it these ways but then I get an UnfinishedStubbingException
:
doReturn("deep").when(mock.getBar()).getName();
doReturn("deep").when(mock.getBar().getName());
How can I use the deep stubbing feature with the doReturn
method?
(I am aware that the use of deep stubbing is discouraged by some, including the Mockito developers. I'm not sure if I agree with their position on this. Let's keep that discussion out of this issue.)
One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test. I strongly recommend only using doReturn/when .
You can use doReturn-when to specify a return value on a spied object without making a side effect. It is useful but should be used rarely. The more you have a better pattern such as MVP, MVVM and dependency injection, the less chance you need to use Mockito. spy .
RETURNS_DEEP_STUBS. An answer that returns deep stubs (not mocks). RETURNS_DEFAULTS. The default configured answer of every mock.
It seems Mockito gets confused when you call your deep stub in then when
method. I was able to work around it by calling mock.getBar()
separately:
Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
Bar bar = mock.getBar();
doReturn("deep").when(bar).getName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With