测试,如果我不想触发整个过程

问题描述

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 Context,可以查看创建sliced context的其他测试注释:

  • @WebMvcTest仅使用与MVC相关的bean创建一个Spring Context
  • @DataJpaTest仅使用与JPA / JDBC相关的bean创建一个Spring Context

除此之外,我还将从您的主条目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
  }


}

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