从TestListenerAdapter访问TestNG测试类的字段



背景

我有以下情况:

  • 我的测试类实现org.testng.ITest
  • 它们都有一个包含当前测试环境信息的Helper(例如,被测设备)

例如:

com.company.appundertest.Helper h;
public class TestClass implements org.testng.ITest {
    private String testName;
    //Helper is initialized externally in Factory + DataProvider 
    //and passed to Constructor.
    public TestClass(com.company.appundertest.Helper hh) {
    this.h = hh;
    //constructor sets the test-name dynamically
    //to distinguish multiple parallel test runs.
    this.testName = "some dynamic test name";
    }
    @Override
    public String getTestName() {
        return this.testName;
    }
    @Test
    public void failingTest() {
        //test that fails...
    }
}
  • 这些测试类使用Factory和并行数据提供程序并行执行
  • 测试失败后,我需要访问失败测试类的Helper实例中的变量。这些将用于识别故障点的环境(例如,拍摄故障设备的屏幕截图)

这个问题本质上可以归结为:

如何访问TestNG测试类中的字段

参考

  • 通过Java中的反射访问私有继承字段

下面是一个示例方法。您可以将其插入到Test Listener类(扩展TestListenerAdapter)中

public class CustomTestNGListener extends TestListenerAdapter{
//accepts test class as parameter.
//use ITestResult#getInstance()
private void getCurrentTestHelper(Object testClass) {
        Class<?> c = testClass.getClass();
        try {
            //get the field "h" declared in the test-class.
            //getDeclaredField() works for protected members.
            Field hField = c.getDeclaredField("h");
            //get the name and class of the field h.
            //(this is just for fun)
            String name = hField.getName();
            Object thisHelperInstance = hField.get(testClass);
            System.out.print(name + ":" + thisHelperInstance.toString() + "n");
            //get fields inside this Helper as follows:
            Field innerField = thisHelperInstance.getClass().getDeclaredField("someInnerField");
            //get the value of the field corresponding to the above Helper instance.
            System.out.println(innerField.get(thisHelperInstance).toString());
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
}

如下调用:

@Override
public void onTestFailure(ITestResult tr) {
        getCurrentTestHelper(tr.getInstance());
}

@Vish的解决方案很好,但您可以使用来避免反射

interface TestWithHelper {
   Helper getHelper();
}

TestClass将在哪里实现它。然后:

private void getCurrentTestHelper(Object testClass) {
  if (testClass instanceof TestWithHelper) {
    Helper helper = ((TestWithHelper) testClass).getHelper();
    ...
  }
}

相关内容

  • 没有找到相关文章

最新更新