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