如何在testNG中自定义通过/失败测试的报告

时间:2014-06-05 13:10:21

标签: java testng

我正在尝试使用testNG执行一些测试。测试方法接受来自dataProviderClass的对象。我想在测试运行时打印Object的名称。我使用了ItestListenrs,但它只打印测试函数的名称而不是其中的Object。

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("");
        }
      }
}

所以目前输出就像PASSED:SampleTest 但我希望输出像PASSED:SampleTest_Object.getStringName()。

1 个答案:

答案 0 :(得分: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();
        }
    }
}