JUnit 5:将Spring组件注入Extension(BeforeAllCallback/AfterAllCallback) [英] JUnit 5: Inject spring components to Extension (BeforeAllCallback / AfterAllCallback)

查看:364
本文介绍了JUnit 5:将Spring组件注入Extension(BeforeAllCallback/AfterAllCallback)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tl; dr :如何在所有测试运行之前将自定义数据提供程序实例化为Spring组件?

是否存在将Spring组件注入到实现BeforeAllCallback的自定义JUnit Jupiter扩展中的明智方法?在使用@ExtendWith(OncePerTestRunExtension.class)执行MyTestClass之前,beforeAll方法应该触发一个复杂的过程.

我创建了一个Spring Boot应用程序(src/main/java),该应用程序为我的测试(src/test/java)提供了必要的数据.数据最多可能需要几个小时才能准备好进行测试.它还使我可以抽象地访问一些其他端点.

在所有测试类的过程之间,数据不会更改.所以我只想提取一次数据.

只在一个类中编写所有测试是可行的,但我认为将其分为不同的类可以提供更好的概述.

解决方案

在自定义BeforeAllCallbackbeforeAll(ExtensionContext)方法中,您可以通过SpringExtension.getApplicationContext(extensionContext)访问当前测试类的Spring ApplicationContext. >

如果将自定义数据提供程序配置为该ApplicationContext中的Spring组件,则可以从扩展内的ApplicationContext中检索该组件-例如,通过applicationContext.getBean(MyDataProvider.class).

如果需要处理数据并在测试之间存储处理过的数据,则可以将其存储在JUnit Jupiter的 root ExtensionContext.Store中.有关详细信息,请参见ExtensionContext.Store中的ExtensionContext.getRoot()getOrComputeIfAbsent(...)变体.

tl;dr: How can I instantiate a custom data provider as a Spring component before all tests run?

Is there a smart way to inject Spring components into a custom JUnit Jupiter extension that implements BeforeAllCallback? The beforeAll method should trigger a complex process before MyTestClass is executed with @ExtendWith(OncePerTestRunExtension.class).

I created a Spring Boot Application (src/main/java) that provides my test (src/test/java) with the necessary data. The data can take up to a few hours to be prepared for the tests. It also gives me abstracted access to some rest-endpoints.

The data does not change in between the process of all test classes. So I just want to pull the data once.

Writing all tests in just one class would work, but I think the separation into different classes gives a better overview.

解决方案

In the beforeAll(ExtensionContext) method of your custom BeforeAllCallback, you can access the Spring ApplicationContext for the current test class via SpringExtension.getApplicationContext(extensionContext).

If you configure your custom data provider as a Spring component in that ApplicationContext, you can then retrieve the component from the ApplicationContext within your extension -- for example, via applicationContext.getBean(MyDataProvider.class).

If you need to process the data and store that processed data between tests, you can store that in the root ExtensionContext.Store in JUnit Jupiter. See ExtensionContext.getRoot() and the getOrComputeIfAbsent(...) variants in ExtensionContext.Store for details.

这篇关于JUnit 5:将Spring组件注入Extension(BeforeAllCallback/AfterAllCallback)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆