2015-12-02 62 views
0

背景接入领域

我有以下情况:

  • 我的测试类实现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的测试类中的字段?

参考

回答

1

这里的示例方法。您可以在测试监听器类插入这个(延伸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()); 
} 
0

的@Vish的解决方案是好的,但你能避免与反思:

interface TestWithHelper { 
    Helper getHelper(); 
} 

其中您的TestClass将执行它。 Then:

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