首页 > 解决方案 > SpringBootTest时如何忽略ContextRefreshedEvent?

问题描述

我正在努力找出如何在正常操作期间忽略一个类方法,该方法应该在 SpringBootApplication 准备好时启动一个线程:

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {

    this.start();
}

在测试的情况下我不想要这样的行为,想从测试方法开始。据我了解是由测试类上的注释ContextRefreshedEvent触发的。@SpringBootTest

标签: spring-bootmockitojunit5spring-boot-test

解决方案


用于测试监听器本身:

您不需要@SpringBootTest对 Spring Boot 应用程序进行每次测试(我认为您实际上需要最少的此类测试,因为它们会加载所有内容。)

还有其他选择:

  • 如果您不需要 Spring 中的任何内容:使用 Mockito 对服务进行单元测试(如果它具有您想要模拟的依赖项)。
  • 否则:使用切片 - 例如@JsonTest将自动配置ObjectMapper和其他使用 JSON 的 bean。其中有很多,因此如果您希望为测试自动配置应用程序的任何部分,请查看文档。

@SpringBootTest从其他测试中排除监听器:

我看到两个选项:

  • 使用@MockBeans.
@SpringBootTest
@MockBeans(@MockBean(Listener.class))
public class SomeTest {
  // ...
}
  • 在特定配置文件中执行测试并将侦听器 bean 标记为仅包含在默认配置文件中。(或者不在“测试”配置文件中。)
@Component
@Profile("default") // OR: @Profile("!test")
public class Listener {
  // ...
}

@SpringBootTest
@ActiveProfiles("test")
public class SomeTest {
  // ...
}

如果您需要 bean 作为另一个服务的依赖项,您可能需要从现有 bean 中提取侦听器。


推荐阅读