背景
我有以下情况:
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...
}
}
这个问题基本归结为:
如何访问TestNG测试类中的字段?
参考
答案 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();
...
}
}