鑑於傳統應用程序有1500個spring.xmls。我想寫一個服務的單元測試。我深深地依賴於地獄。我必須接受應用程序,沒有出路。在糾結的春天背景下進行單元測試
所以我們使用spring-3.something和mockito-1.9,我想要測試服務的好方法。較新的代碼大量使用@Autowired註釋。
這個服務間接地使用了我實際上想在測試中使用的〜25個助手(工廠方法等)以及我對這個測試不感興趣的〜25個對象。
我目前嘗試以上述方式設置上下文,但我對@Mock,@InjectMocks,@Autowired的影響感到困惑。
我的測試如下。我需要幫助才能正確設置它。
問題:
- 是什麼@InjectMocks的實際效果?
- 我該如何決定(技術上)哪些自動佈線的豆子真的被使用,哪些被mock取代?
- 我知道,我濫用嘲諷獲得假貨。是否有一種更簡單的方法來獲得單線的假貨?
- * 請注意,我想明白這一點,因爲我有這樣的服務... *
這裏的負載是我的示例:
@ContextConfiguration(locations = {
"classpath:/some/path/MainTestConfig.spring.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
public class SampleTest {
// *** Uninteresting Dependencies to be mocked *** //
@Mock Mock1 mock1;
@Mock Mock2 mock2;
/** Service under test */
@Autowired
SomeService service;
// *** Tightly coupled helpers to be used *** //
@Autowired Helper1 helper1
@Autowired Helper2 helpr2
@Before
public void setup() {
MockitoAnnotations.initMocks(SampleTest.class);
}
@Test
public void testSample() {
// prepare dummy context
SomeContext context = new Context();
// define expected result
int expectedValue = 42;
//execute method under test, record result
Result actualResult = service.execute(context);
//make assertions on result
assertTrue(actualResult.getSomething()==expectedValue);
}
}
我不明白爲什麼你會有'mock1'和'mock2'這些在你的測試中似乎沒有關係,因爲它們是不相關的。此外,助手似乎不被使用,在測試中得到驗證。如果一切都是春天連線,爲什麼你想要它。我相信你實際上應該嘲笑緊密耦合的幫手,並驗證相互作用。最終你也可以把這個測試寫成一個大功能/特性測試,即不是單元測試,也不是集成測試,因此它會被放置在其他一些軟件包中以顯示你的同事的不同之處。 – Brice
順便問一下你是否嘗試過Spring 3中的註釋配置?如果你只需要注入一些依賴關係,這可能會很有用,並且這也可以用於mock(如果添加另一個maven依賴關係,則不需要使用springockito)。 – Brice