所以我明白在Mockito @InjectMocks中会注入@Mock的注释,但是如何处理这种情况呢?
@Mock
private MockObject1 mockObject1;
@Mock
private MockObject2 mockObject2;
@InjectMocks
private SystemUnderTest systemUnderTest = new SystemUnderTest();
想象一下,MockObject2的属性类型为MockObject1,而SystemUnderTest的属性类型为MockObject2。我想将mockObject1注入mockObject2,并将mockObject2注入systemUnderTest。
这可以用注释吗?
答案 0 :(得分:23)
由于我在这里没有得到任何回复,我在Mockito论坛上提问。以下是讨论的链接:https://groups.google.com/d/topic/mockito/hWwcI5UHFi0/discussion
总结答案,从技术上讲,这会挫败嘲笑的目的。您应该只模拟SystemUnderTest类所需的对象。在自己模仿的物体中嘲弄东西是没有意义的。
如果你真的想这样做,@ spy可以提供帮助
答案 1 :(得分:16)
将@Spy与@InjectMocks结合使用是可能的。对于您的示例,它将是:
@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;
答案 2 :(得分:4)
这对我有用:
private MockObject1 mockObject1 = mock(MockObject1.class);
@Spy
private RealObject2 realObject = new RealObject2(mockObject1);
@InjectMocks
private SystemUnderTest systemUnderTest = new SystemUnderTest();
答案 3 :(得分:4)
我发现的其他解决方案是使用java sintax代替注释来注入@Spy对象。
@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;