junit5:从测试类访问扩展字段

t3psigkw  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(336)

我需要在使用它的类中的所有测试用例之前和之后使用扩展来运行代码。我的测试类需要访问扩展类中的字段。这可能吗?
鉴于:

@ExtendWith(MyExtension.class)
public class MyTestClass {

    @Test
    public void test() {
        // get myField from extension and use it in the test
    }
}

public class MyExtension implements 
  BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {

    private int myField;

    public MyExtension() {
        myField = someLogic();
    }

    ...
}

如何访问 myField 从我的测试班?

c7rzv4ha

c7rzv4ha1#

您可以通过标记注解和 BeforeEachCallback 分机。
创建一个特殊的标记注解,例如。

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyField {
}

使用注解从扩展名中查找和设置值:

import org.junit.jupiter.api.extension.BeforeEachCallback;

public class MyExtension implements BeforeEachCallback {

    @Override
    public void beforeEach(final ExtensionContext context) throws Exception {
        // Get the list of test instances (instances of test classes) 
        final List<Object> testInstances = 
            context.getRequiredTestInstances().getAllInstances();

        // Find all fields annotated with @MyField
        // in all testInstances objects.
        // You may use a utility library of your choice for this task. 
        // See for example, https://github.com/ronmamo/reflections 
        // I've omitted this boilerplate code here. 

        // Assign the annotated field's value via reflection. 
        // I've omitted this boilerplate code here. 
    }

}

然后,在测试中,对目标字段进行注解,并使用扩展名扩展测试:

@ExtendWith(MyExtension.class)
public class MyTestClass {

    @MyField
    int myField;

    @Test
    public void test() {
        // use myField which has been assigned by the extension before test execution
    }

}

注意:您也可以扩展 BeforeAllCallback 它在类的所有测试方法之前执行一次,具体取决于您的实际需求。

相关问题