从TestListenerAdapter访问TestNG测试类的字段

时间:2015-12-02 11:21:14

标签: reflection 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测试类中的字段?

参考

2 个答案:

答案 0 :(得分:1)

这是一个示例方法。您可以将它插入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());
}

答案 1 :(得分:0)

@Vish的解决方案很好,但你可以避免反思:

interface TestWithHelper {
   Helper getHelper();
}

您的TestClass将在哪里实施。 然后:

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