SpringBootTest时如何忽略ContextRefreshedEvent?

How to ignore ContextRefreshedEvent when SpringBootTest?

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

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {

    this.start();
}

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

上触发的

用于测试监听器本身:

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

还有其他选项:

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

为了从其他 @SpringBootTest 测试中排除侦听器:

我看到两个选项:

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

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

如果您需要将 bean 作为其他服务的依赖项,则可能需要从现有 bean 中提取侦听器。