3
我有一個Spring Boot 1.4.2應用程序。在啓動過程中使用的一些代碼如下所示:在應用程序啓動前配置@MockBean組件
@Component class SystemTypeDetector{
public enum SystemType{ TYPE_A, TYPE_B, TYPE_C }
public SystemType getSystemType(){ return ... }
}
@Component public class SomeOtherComponent{
@Autowired private SystemTypeDetector systemTypeDetector;
@PostConstruct public void startup(){
switch(systemTypeDetector.getSystemType()){ // <-- NPE here in test
case TYPE_A: ...
case TYPE_B: ...
case TYPE_C: ...
}
}
}
存在確定系統類型的組件。該組件在其他組件啓動時使用。在生產一切正常。
現在我想添加使用Spring 1.4的@MockBean一些集成測試。
測試看起來是這樣的:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyWebApplication.class, webEnvironment = RANDOM_PORT)
public class IntegrationTestNrOne {
@MockBean private SystemTypeDetector systemTypeDetectorMock;
@Before public void initMock(){
Mockito.when(systemTypeDetectorMock.getSystemType()).thenReturn(TYPE_C);
}
@Test public void testNrOne(){
// ...
}
}
基本上嘲諷的正常工作。我使用了systemTypeDetectorMock,如果我呼叫getSystemType
- >TYPE_C
被返回。
問題是,應用程序不啓動。目前,彈簧工作秩序似乎是:
- 創建所有嘲笑(不配置的所有方法返回null)
- 開始應用
- 電話@之前的方法(其中嘲笑將被配置)
- 啓動測試
我的問題是應用程序以未初始化的模擬開始。所以對getSystemType()
的調用返回null。
我的問題是:如何在應用程序啓動之前配置模擬?
編輯:如果有人有同樣的問題,一個解決辦法是使用@MockBean(answer = CALLS_REAL_METHODS)
。這稱爲真實組件,在我的情況下,系統啓動。啓動後,我可以更改模擬行爲。
你可以注入模擬,並在此答案由描述稱手的初始化代碼:http://stackoverflow.com/a/31587946/3440376 – tan9