Multiple levels of @Mock and @InjectMocks

后端 未结 4 1325
星月不相逢
星月不相逢 2021-02-01 13:07

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         


        
相关标签:
4条回答
  • 2021-02-01 13:49

    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;
    
    0 讨论(0)
  • 2021-02-01 13:51

    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

    0 讨论(0)
  • 2021-02-01 14:02

    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;
    
    0 讨论(0)
  • 2021-02-01 14:04

    This works for me:

    private MockObject1 mockObject1 = mock(MockObject1.class);
    
    @Spy
    private RealObject2 realObject = new RealObject2(mockObject1);
    
    @InjectMocks
    private SystemUnderTest systemUnderTest = new SystemUnderTest();
    
    0 讨论(0)
提交回复
热议问题