【问题标题】:How to get variable value in extensionContext如何在extensionContext中获取变量值
【发布时间】:2020-05-04 17:15:59
【问题描述】:

如何将结果字段的值放入我的 TestReporter 类?

@ExtendWith({TestReporter.class})
private TestClass{
   String result;

   @Test
   void testA(){
     //some action here
     result = some result;
   }
}
public class TestReporter implements BeforeAllCallback, BeforeTestExecutionCallback, AfterAllCallback,
       TestWatcher {
    private static ExtentHtmlReporter htmlReporter;
    private static ExtentReports extent;
    private static ExtentTest test;

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
       //set up extent report
    }


   @Override
   public void testSuccessful(ExtensionContext context) {
     //not possible, but desired
     test.pass(context.getElement.get("result"), MediaEntityBuilder.createScreenCaptureFromPath("test"+count+".png").build());

   }

}

我一直在研究如何做到这一点,但不确定我正在寻找的东西是否可能或如何实施

【问题讨论】:

    标签: java unit-testing junit junit5


    【解决方案1】:

    TLDR;

    在必须实现适当回调的扩展中使用反射,例如AfterEachCallback。通过context.getRequiredTestInstance()抓取测试类的实例。

    加长版

    @ExtendWith(TestReporter.class)
    public class TestClass {
    
        String result;
    
        @Test
        void testA() {
            result = "some result";
        }
    }
    
    class TestReporter implements AfterEachCallback {
        @Override
        public void afterEach(final ExtensionContext context) throws Exception {
            Object testInstance = context.getRequiredTestInstance();
    
            Field resultField = testInstance.getClass().getDeclaredField("result");
    
            String resultValue = (String) resultField.get(testInstance);
    
            System.out.println("Value of result: " + resultValue);
        }
    }
    

    请注意,AfterAllContext 无权访问测试实例,因为每个测试方法都有一个实例。使用TestWatcher 代替AfterEachCallback 也可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多