問題描述
所以我知道在 Mockito 中,@InjectMocks 會通過 @Mock 的注解注入任何它可以注入的東西,但是如何處理這種情況呢?
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 MockObject1 mockObject1;
@Mock
private MockObject2 mockObject2;
@InjectMocks
private SystemUnderTest systemUnderTest = new SystemUnderTest();
假設(shè) MockObject2 有一個 MockObject1 類型的屬性,而 SystemUnderTest 有一個 MockObject2 類型的屬性.我想將 mockObject1 注入到 mockObject2 中,并將 mockObject2 注入到 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.
這可以通過注釋實現(xiàn)嗎?
Is this possible with annotations?
推薦答案
由于我在這里沒有得到任何回復(fù),所以我在 Mockito 論壇上提問.這是討論的鏈接:https://groups.google.com/d/topic/mockito/hWwcI5UHFi0/討論
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
總結(jié)答案,從技術(shù)上講,這會破壞嘲笑的目的.您實際上應(yīng)該只模擬 SystemUnderTest 類所需的對象.在本身就是模擬的對象中模擬事物是毫無意義的.
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.
如果你真的想這樣做,@spy 可以提供幫助
If you really wanted to do it, @spy can help
這篇關(guān)于多個級別的@Mock 和@InjectMocks的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!