Java – Multiple levels of @Mock and @InjectMocks


So I understand that in Mockito @InjectMocks will inject anything that it can with the annotation of @Mock, but how to handle this scenario?

private MockObject1 mockObject1;

private MockObject2 mockObject2;

private SystemUnderTest systemUnderTest = new SystemUnderTest();

Imagine that MockObject2 has an attribute that is of type MockObject1, and SystemUnderTest has an attribute of type MockObject2. I would like to have mockObject1 injected into mockObject2, and mockObject2 injected into systemUnderTest.

Is this possible with annotations?

Best Solution

Since I didn't get any response here I asked on the Mockito forums. Here is a link to the discussion:

To summarize the answers, technically this would kind of defeat the purpose of mocking. You should really only mock the objects needed by the SystemUnderTest class. Mocking things within objects that are themselves mocks is kind of pointless.

If you really wanted to do it, @spy can help