Mockito: using a method in "thenReturn" to return a mock doesn't work
This is indeed a limitation of Mockito, and it is referenced in their FAQ:
Can I
thenReturn()
an inlinedmock()
?Unfortunately you cannot do this:
when(m.foo()).thenReturn(mock(Foo.class)); // ^
The reason is that detecting unfinished stubbing wouldn't work if we allow above construct. We consider is as a 'trade off' of framework validation (see also previous FAQ entry). However you can slightly change the code to make it working:
//extract local variable and start smiling: Foo foo = mock(Foo.class); when(m.foo()).thenReturn(foo);
The workaround, as mentioned, is to store the desired returned value in a local variable, like you have done.
The way I understand it is that Mockito validates the usage you make of it every time you call its methods. When another method is called during an on-going stubbing process, you are breaking its validation process.