【问题标题】:How to ignore ContextRefreshedEvent when SpringBootTest?SpringBootTest时如何忽略ContextRefreshedEvent?
【发布时间】:2020-02-27 17:48:35
【问题描述】:

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

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {

    this.start();
}

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

【问题讨论】:

  • 您好,您找到上述解决方案了吗?

标签: spring-boot mockito junit5 spring-boot-test


【解决方案1】:

用于测试监听器本身:

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

还有其他选择:

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

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

我看到两个选项:

  • 使用 @MockBeans 模拟侦听器 bean。
@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 中提取侦听器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-30
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2022-01-06
    • 2018-09-23
    • 2020-08-28
    相关资源
    最近更新 更多