Java 自定义测试应用程序上下文

Java 自定义测试应用程序上下文,java,junit5,spring-test,spring-boot-test,Java,Junit5,Spring Test,Spring Boot Test,我一直在拼命尝试构建一个扩展,它需要来自JUnit5扩展模型和Spring启动测试框架的信息。具体地说,我想使用ApplicationContext初始值设定项和自定义注释连接到ApplicationContext创建过程: @Retention(RUNTIME) @Target(TYPE) @ContextConfiguration(initializers = CustomContextInitializer.class) public @interface CustomAnnotation

我一直在拼命尝试构建一个扩展,它需要来自JUnit5扩展模型和Spring启动测试框架的信息。具体地说,我想使用
ApplicationContext初始值设定项
和自定义注释连接到ApplicationContext创建过程:

@Retention(RUNTIME)
@Target(TYPE)
@ContextConfiguration(initializers = CustomContextInitializer.class)
public @interface CustomAnnotation {
    String someOption();
}
测试结果如下所示:

@SpringBootTest
@CustomAnnotation(someOption = "Hello There")
public class SomeTest {
    ...
}
现在,如何从我的
CustomContextInitializer
中访问测试类的
CustomAnnotation
实例

class CustomContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {

        // How to access the Test Class here?

        CustomAnnotation annotation = <Test Class>.getAnnotation(CustomAnnotation.class);
        System.out.println(annotation.someOption());
    }
}
类CustomContextInitializer实现ApplicationContextInitializer{
@凌驾
public void初始化(ConfigurableApplicationContext applicationContext){
//如何在这里访问测试类?
CustomAnnotation=.getAnnotation(CustomAnnotation.class);
System.out.println(annotation.someOption());
}
}

在创建ApplicationContext期间,是否可以以某种方式访问JUnit5
ExtensionContext
?它不必来自
ApplicationContextInitializer
。我只需要一个执行得足够早的钩子,这样我就可以在整个bean实例化过程实际开始之前注入一些动态生成的属性。

请查看
@DynamicPropertySource
,了解如何在bean初始化之前注入属性。然后,您可以使用
@RegisterExtension
注册一个自定义扩展,该扩展读取注释属性,并通过某种方法使其可用:

@CustomAnnotation(someOption=“你好”)
公共类测试{
@注册扩展
静态CustomExtension扩展=新CustomExtension();
@动态属性源
静态无效注册表属性(DynamicPropertyRegistry注册表){
registry.add(“property.you.need”,
()->customExtension.getProperty());
}
}
公共类CustomExtension实现BeforeAllCallback{
私有财产;
公共字符串getProperty(){
归还财产;
}
@凌驾
public void beforeAll(ExtensionContext上下文)引发异常{
CustomAnnotation=context.getRequiredTestClass()
.getAnnotation(CustomAnnotation.class);
property=annotation.someOption();
}
}

我知道它没有回答关于用Spring初始化机制挂接JUnit 5的问题,但是如果动态属性是您所需要的,那么这正好解决了这个问题。

您可以实现自己的
TestExecutionListener
并使用它访问您提到的注释

@Retention(RUNTIME)
@Target(ElementType.TYPE)
@TestExecutionListeners(listeners = CustomTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
@interface CustomAnnotation {
    String someOption();
}

static class CustomTestExecutionListener implements TestExecutionListener {
    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
       final CustomAnnotation annotation = testContext.getTestClass().getAnnotation(CustomAnnotation.class);
       System.out.println(annotation.someOption());
    }
}


问题是,我想使用注释的属性来生成我的自定义属性,因此我需要访问注释实例。我可能错了,但据我所知,没有简单的方法可以做到这一点。为了反映这一点,我改变了答案。可以使用
@RegisterExtension
注册读取注释属性的自定义扩展。