So I understand that in Mockito @InjectMocks will inject anything that it can with the annotation of @Mock, but how to handle this scenario?
@Mock
private MockOb
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;
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
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;
This works for me:
private MockObject1 mockObject1 = mock(MockObject1.class);
@Spy
private RealObject2 realObject = new RealObject2(mockObject1);
@InjectMocks
private SystemUnderTest systemUnderTest = new SystemUnderTest();