如何在extensionContext中获取变量值

How to get variable value in extensionContext

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

@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());

   }

}

我一直在研究实现此目的的方法,但不确定我正在寻找的东西是否可行或如何实现

TLDR;

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

抓取测试实例class

长版

@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 也可以。