Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep stubbing together with the doReturn method

Tags:

java

mockito

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.)

like image 947
Lii Avatar asked Jun 17 '15 07:06

Lii


People also ask

What is the difference between doReturn and thenReturn?

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 .

What is doReturn in Mockito?

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 .

What is answers Returns_deep_stubs?

RETURNS_DEEP_STUBS. An answer that returns deep stubs (not mocks). RETURNS_DEFAULTS. The default configured answer of every mock.


1 Answers

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();
like image 74
K Erlandsson Avatar answered Sep 28 '22 21:09

K Erlandsson