spring-boot - SpringBootTest时如何忽略ContextRefreshedEvent?
问题描述
我正在努力找出如何在正常操作期间忽略一个类方法,该方法应该在 SpringBootApplication 准备好时启动一个线程:
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
this.start();
}
在测试的情况下我不想要这样的行为,想从测试方法开始。据我了解是由测试类上的注释ContextRefreshedEvent
触发的。@SpringBootTest
解决方案
用于测试监听器本身:
您不需要@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 中提取侦听器。
推荐阅读
- vue.js - Nested Vue transitions: one transition works, the other doesn't
- ruby-on-rails - Apple Push Notification 服务服务器证书更新 SSL 错误
- c# - 传递连接表以查看模型 Asp.Net Core
- dart - 从父类访问子类构造函数
- python - 在 MacOS 上使用 Python3 进行 cvxopt
- python-3.x - 在接受消息框消息后,第二个 tkinter 屏幕需要处于活动状态
- npm - 秘银依赖不断给本地化电子应用程序带来问题
- sas - 我不断在 SAS 中遇到错误
- c# - 传递 ExecutionContext(流)VS 捕获它?
- json - 为什么我无法在 swift 中使用 JSON 参数再删除一个 CollectionVIew Cell?