Multiple levels of @Mock and @InjectMocks

Since I didn't get any response here I asked on the Mockito forums. Here is a link to the discussion: https://groups.google.com/d/topic/mockito/hWwcI5UHFi0/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


It is possible by combining @Spy with @InjectMocks. For your example, it would be:

@Spy
private MockObject1 mockObject1 = new MockObject1 ();

@Spy @InjectMocks //if MockObject2 has a MockObject1, then it will be injected here.
private MockObject2 mockObject2 = new MockObject2 ();

@InjectMocks
private SystemUnderTest systemUnderTest;

Other solution I found is using java sintax instead annotation to make the @Spy object injected.

@Spy
private MockObject1 mockObject1 = new MockObject1 ();

@InjectMocks //if MockObject2 has a MockObject1, then it will be injected here.
private MockObject2 mockObject2 = spy(MockObject2.class);

@InjectMocks
private SystemUnderTest systemUnderTest;

Tags:

Java

Mockito