【问题标题】:SpringBootTest: how to know when boot application is doneSpringBootTest:如何知道启动应用程序何时完成
【发布时间】:2017-02-15 16:29:11
【问题描述】:
Spring boot 集成测试长这样
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application)
class IntegrationTest {
static QpidRunner qpidRunner
@BeforeClass
static void init() {
qpidRunner = new QpidRunner()
qpidRunner.start()
}
@AfterClass
static void tearDown() {
qpidRunner.stop()
}
}
因此,Qpid 实例在所有测试之前运行并在所有测试之后拆除。我想知道有没有办法在调用qpidRunner.stop()之前检查spring boot应用程序是否仍在运行。只有当我确定 spring 应用程序已完成停止时,我才想停止 Qpid。
【问题讨论】:
标签:
spring
spring-boot
spring-test
qpid
【解决方案1】:
Spring Boot 集成测试可以配置一个ApplicationListener 来监听ContextClosedEvent。在测试类中定义一个嵌套的 @TestConfiguration 类,以将 bean 添加到应用程序的主要配置中。
@TestConfiguration
static class MyConfiguration {
@Bean
public ApplicationListener<ContextClosedEvent> contextClosedEventListener() {
return event -> qpidRunner.stop();
}
}
【解决方案2】:
考虑到ConfigurableWebApplicationContext可以注入SpringBootTest,在代码中加入这行就解决了问题
static ConfigurableWebApplicationContext context
@Autowired
void setContext(ConfigurableWebApplicationContext context) {
AbstractDocsIntegrationTest.context = context
}
@AfterClass
static void tearDown() {
context.stop()
qpidRunner.stop()
}
关于 stop method 的 Spring 文档
停止这个组件,通常以同步方式,这样
组件在此方法返回时完全停止。
JUnit AfterClass 注解的方法必须是静态的,因此@Autowired 使用 setContext 方法解决。