2015-12-02 66 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(); 
    ... 
    } 
}