【问题标题】:JUnit5: access extension field from test classJUnit5:从测试类访问扩展字段
【发布时间】:2020-12-02 19:03:13
【问题描述】:

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

给定:

@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

【问题讨论】:

    标签: java junit junit5


    【解决方案1】:

    您可以通过标记注释和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,它在类的所有测试方法之前执行一次,具体取决于您的实际需求。

    【讨论】:

      猜你喜欢
      • 2022-07-05
      • 1970-01-01
      • 2021-03-07
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 2019-07-04
      • 2020-12-14
      相关资源
      最近更新 更多