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 inlined mock()?

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.


You can't use a method in thenReturn, but you can in thenAnswer Your code will be called after the when condition will occur, unlike any workaround based on thenReturn

Thus you could write:

@Test
public void nowWorkingTest() {
    Mockito.when(mockedFirstObject.getSecondObject()).thenAnswer(new Answer<Map>() {
        @Override
        public Map answer(InvocationOnMock invocation) {
            return setupMockedSecondObject();
        }
    });
    Assert.assertEquals(mockedFirstObject.getSecondObject().getName(), "MockObject");
}

Let find another example here