Spring boot 测试,如果我没有';我不想触发整个事件
Spring启动应用程序Spring boot 测试,如果我没有';我不想触发整个事件,spring-boot,spring-test,Spring Boot,Spring Test,Spring启动应用程序 @SpringBootApplication @EnableScheduling @Slf4j public class MyApplication { @Autowired private ApplicationEventPublisher publisher; ... @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { ...
@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上下文,可以查看创建以下内容的其他测试注释:
仅使用MVC相关bean创建Spring上下文@WebMvcTest
创建一个只有JPA/JDBC相关bean的Spring上下文@DataJpaTest
- 等等
CommandLineRunner
。否则,上面的注释也会触发逻辑
因此,您可以将其外包给另一个@组件
类:
@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”)
来仅在特定概要文件处于活动状态时填充它们。这样,如果您不需要,您可以在所有集成测试中包括或扩展它们,例如,始终使用此启动逻辑。非常感谢您的输入。我需要编写测试的逻辑是应用程序的核心部分。从逻辑上讲,这些切片上下文都不适用。我想我仍然需要一个这样我就可以对功能进行测试了。我可能会为测试设置一个配置文件,这样它就不会加载您演示的组件。只是为了将来的参考做一个小的修改,commandLineRunner需要作为一个组件来实现,例如MyCommandLineRunner实现commandLineRunner{…}。