Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 测试,如果我没有';我不想触发整个事件_Spring Boot_Spring Test - Fatal编程技术网

Spring boot 测试,如果我没有';我不想触发整个事件

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) { ...

Spring启动应用程序

@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上下文
  • @DataJpaTest
    创建一个只有JPA/JDBC相关bean的Spring上下文
  • 等等
除此之外,我还将从主入口Spring Boot入口点类中删除您的
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{…}。