测试,如果我不想触发整个事情

Test, if I don't want to trigger the whole thing

A​​ 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{
   ...
} 

我在 class 中开始一个测试用例后,整个链事件发生,即读取文件、发布事件和事件侦听器相应地采取行动。

避免在 运行 测试期间发生此类连锁事件的最佳方法是什么?

如果您想避免为所有集成测试启动整个 Spring 上下文,您可以查看其他创建 sliced context:[=17= 的测试注释]

  • @WebMvcTest 创建一个 Spring 仅包含 MVC 相关 bean 的上下文
  • @DataJpaTest 创建一个 Spring 上下文,只有 JPA/JDBC 个相关 bean
  • 等等

除此之外,我还将从您的主入口 Spring 引导入口点 class 中删除您的 CommandLineRunner。否则上面的注释也会触发逻辑。

因此你可以将它外包给另一个 @Component class:

@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
  }


}

除此之外,您还可以在 Spring bean 上使用 @Profile("production"),以便仅在特定配置文件处于活动状态时填充它们。这样,如果您不想要,您可以在所有集成测试中包含或排除它们。这个启动逻辑总是。