2014-06-05 65 views
0

我正在尝试使用testNG执行一些测试。该测试方法接受来自dataProviderClass的对象。我想在测试运行时打印对象的名称。我使用了ItestListenrs,但这只是打印测试函数的名称而不是其中的Object。如何在testNG中自定义合格/失败测试报告

SampleTest.java:

package com.abc; 

import org.testng.annotations.Listeners; 
import org.testng.annotations.Test; 
@Listeners({ com.mindtree.MyListener.class}) 
public class SampleTest { 

    @Test(dataProviderClass = templateObject.class) 
    public void SampleTest() throws Exception{ 
     //do some assertion on Object values; 
    } 
    } 

MyListener.java:

package com.abc; 

import org.testng.ITestResult; 
import org.testng.TestListenerAdapter; 

public class MyListener extends TestListenerAdapter { 

    private int m_count = 0; 

     @Override 
     public void onTestFailure(ITestResult tr) { 
     log("Fail"); 
     } 

     @Override 
     public void onTestSkipped(ITestResult tr) { 
     log("Skipped"); 
     } 

     @Override 
     public void onTestSuccess(ITestResult tr) { 
     String className = tr.getMethod().getTestClass().getName(); 
     System.out.println(className); 
     ## WANT TO PRINT HERE THE TESTCASE OBJECT NAME 
     } 

     private void log(String string) { 
     System.out.print(string); 
     if (++m_count % 40 == 0) { 
      System.out.println(""); 
     } 
     } 
} 

所以目前输出来像通过:SampleTest 但我想输出到像PASSED :SampleTest_Object.getStringName()。

回答

0

试试这个:

public class MyListener extends TestListenerAdapter { 

    @Override 
    public void onTestSuccess(ITestResult r) { 
      // Step 1: Find which iteration it is and subtract by 1 to get index 
     int cnt = r.getMethod().getCurrentInvocationCount() -1 ; 

      // Step 2: Get the data provider class instance 
     Class dpc = r.getMethod().getConstructorOrMethod().getMethod().getAnnotation(org.testng.annotations.Test.class).dataProviderClass(); 
      // Step 3: Get the data provider name, which will be method name in dataprovider class. 
     String dp = r.getMethod().getConstructorOrMethod().getMethod().getAnnotation(org.testng.annotations.Test.class).dataProvider(); 
      // Step 4: Now call the method (it is static method) to get all the objects 
     try { 
      Object[][] data = (Object[][]) dpc.getMethod(dp, null).invoke(null); 
        // Step 5: You have data and index... reach out to the data with which your test was run. 
      System.out.println("Successfully got the data"); 
      for (Object o: data[cnt]) { 
       System.out.println(" " + o); 
      } 
     } catch (IllegalAccessException | IllegalArgumentException 
       | InvocationTargetException | NoSuchMethodException 
       | SecurityException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 
相关问题