Lii
Lii

Reputation: 12112

Deep stubbing together with the doReturn method

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

Upvotes: 11

Views: 3699

Answers (1)

K Erlandsson
K Erlandsson

Reputation: 13696

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();

Upvotes: 14

Related Questions