一个Spring Boot应用程序
@SpringBootApplication
@EnableScheduling
@Slf4j
public class MyApplication {
@Autowired
private ApplicationEventPublisher publisher;
...
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
...
// read data from a file and publishing an event
}
}
对于集成测试,我有一些典型的东西。
@SpringBootTest
public class TestingMyApplicationTests{
...
}
在类中启动一个测试用例后,会发生全链事件,即读取文件、发布事件和事件侦听器相应地进行操作。
在运行测试期间,避免此类连锁事件发生的最佳方法是什么?
如果你想避免所有集成测试都启动整个Spring上下文,你可以看看其他创建切片上下文的测试注释:
@WebMvcTest
只使用MVC相关的bean创建Spring Context@DataJpaTest
只使用与JPA/JDBC相关的bean创建Spring上下文- 等等
除此之外,我还将从主入口Spring Boot入口点类中删除CommandLineRunner
。否则,上面的注释也会触发逻辑。
因此,您可以将其外包给另一个@Component
类:
@Component
public class WhateverInitializer implements CommandLineRunner{
@Autowired
private ApplicationEventPublisher publisher;
// ...
@Override
public void run(String... args) throws Exception {
...
// read data from a file and publishing an event
}
}
除此之外,您还可以在Springbean上使用@Profile("production")
,仅在特定概要文件处于活动状态时填充它们。这样,如果你不想要的话,你可以在所有的集成测试中包括或排除它们,例如,总是这样的启动逻辑。