java - 如何在运行时为当前测试ApplicationContext注册Spring Context事件

标签 java spring spring-boot junit junit5

背景:

我的目标是在 Spring 环境中执行 JUnit 5 测试时收集各种时间戳,以创建不同任务的持续时间的统计数据。 (Repository for reference)

因为我无法触及实际的测试代码,所以我必须注册回调,如 ContextRefreshedEvent来 self 的 JUnit Jupiter 扩展。目前我正在注册these callbacksSpring configuration object并希望通过测试应用程序中的某些组件扫描发现这一点。正如您可以想象的那样,这并不适用于每个测试环境。

问题:

我希望我能以某种方式在 my first callback method from JUnit 中手动注册这些事件,例如 ContextRefreshedEvent 。据我了解,这需要我在运行时添加包含回调到当前运行的 Spring Context 的配置或组件。

这可能吗?或者您知道我最初的问题有其他解决方案吗?我非常感谢您就这个问题提供的任何意见,因为我已经为此工作了很长一段时间。

提前非常感谢您!

最佳答案

更新:

Spring Framework 5.2 将内置对测试事件的支持。请参阅GitHub issue 18490了解详情。


在 Spring ApplicationContext 中触发测试相关事件的最佳方法是实现一个自定义 (Spring) TestExecutionListener,它通过 ApplicationEventPublisher API(ApplicationContext 实现)。

您可以通过 TestContext#getApplicationContext() 在自定义 TestExecutionListener 的生命周期方法中访问测试的 ApplicationContext

为了避免接触测试代码,您可以让 Spring 自动注册您的自定义 TestExecutionListener,如下所述:https://docs.spring.io/spring/docs/5.1.4.RELEASE/spring-framework-reference/testing.html#testcontext-tel-config-automatic-discovery

然后,您的自定义 TestExecutionListener 将自动应用于通过 Spring TestContext Framework 运行的所有测试 - 除非给定的测试类配置为覆盖默认监听器(例如,通过 @TestExecutionListeners (...))。

有关相关讨论,请参阅以下 Spring JIRA 问题:

问候,

Sam(Spring TestContext 框架的作者)

关于java - 如何在运行时为当前测试ApplicationContext注册Spring Context事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54114640/

相关文章:

java - 在java中初始化byte[]

java - 记录java中排序算法比较的元素

java - 在 JDBC 中使用日历对象

java - Spring Boot 中仅在请求记录 CommonsRequestLoggingFilter 之前设置

java - 当我点击java按钮时什么也没有发生

java - Spring - 与现有的、不兼容的同名和类的 bean 定义冲突

javascript - 来自 Javascript 的 Spring 基本身份验证凭据

java - Mono 的 doOnSuccess 与 doOnNext 之间有区别吗?

spring-boot - 在 maven 中使用 jgitver 和本地 repo 时无效的 spring-boot-dependency 版本

mysql - 组织.apache.ibatis.type.TypeException : Could not set parameters for mapping: ParameterMapping