How to register Spring Context Events for current test ApplicationContext at runtime

别说谁变了你拦得住时间么 提交于 2021-01-27 17:53:36

问题


Background:

My goal is to collect various timestamps while executing JUnit 5 tests in a Spring environment to create a statistic of the durations of the different tasks. (Repository for reference)

Because I can't touch the actual test code, I have to register callbacks like the ContextRefreshedEvent from within my JUnit Jupiter extension. Currently I am registering these callbacks in a Spring configuration object and hope that this is found by some component scan in the test application. As you can imagine this does not work reliably for every test context.

Problem:

I hope that I can somehow register these events like the ContextRefreshedEvent manually in my first callback method from JUnit. As far as I understand, this requires me to add either a Configuration or a Component containing the callbacks to the currently running Spring Context at runtime.

Is that possible or do you know any other solution to my initial problem? I would really appreciate any input you have on this issue because I am working on this for quite a while now.

Thank you very much in advance!


回答1:


Update:

Spring Framework 5.2 will have built-in support for test events. See GitHub issue 18490 for details.


The best way to fire test-related events in a Spring ApplicationContext is to implement a custom (Spring) TestExecutionListener that fires the events via the ApplicationEventPublisher API (which ApplicationContext implements).

You can access the test's ApplicationContext within lifecycle methods in your custom TestExecutionListener via TestContext#getApplicationContext().

To avoid having to touch test code, you can have Spring automatically register your custom TestExecutionListener, as described here: https://docs.spring.io/spring/docs/5.1.4.RELEASE/spring-framework-reference/testing.html#testcontext-tel-config-automatic-discovery

Your custom TestExecutionListener will then be automatically applied to all tests run via the Spring TestContext Framework -- unless a given test class is configured to override the default listeners (e.g., via @TestExecutionListeners(...)).

For related discussion, see the following Spring JIRA issues:

  • https://jira.spring.io/browse/SPR-8710
  • https://jira.spring.io/browse/SPR-13916

Regards,

Sam (author of the Spring TestContext Framework)



来源:https://stackoverflow.com/questions/54114640/how-to-register-spring-context-events-for-current-test-applicationcontext-at-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!