Search code examples
javatestngtestng-dataprovider

How to call instances of input arguments of TestNg @Test method, after test execution using TestNg ITestResult interface or any other testNg interface


I create a custom reporter implementing IReporter interface and would like to post test input params into final test report. My test input params are provided via TestNg Dataprovider. Every input param is an instance of TestCase class.

I can get to the input params in my report, but it's only a hashcode of the object, not the instance itself, from which I could call needed test data and post in html report.

I was able to print all input arguments using the following code

Set<ITestResult> failedTests = testContext
                    .getFailedTests()
                    .getAllResults();
            for (ITestResult result: failedTests) {
                for (Object param: result.getParameters()) {
                    System.out.println(param);
                }
            }
Output:
data.service.entities.TestCase@1a1da881
org.testng.TestRunner@4dbb42b7

getParameters() method returns an array of objects, which I don't know how to cast to TestCase.

Please advise a way to get the instance of data.service.entities.TestCase@1a1da881 in order to call its methods.


Solution

  • In order to get instances, I created TestNg CustomListener class, where I manually set the input argument (TestCase) as an attribute of every executed test ITestResult:

        public class CustomListener extends TestListenerAdapter {
    
        @Override
        public void onTestFailure(ITestResult iTestResult) {
            super.onTestFailure(iTestResult);
            TestCase tCase = (TestCase) iTestResult.getParameters()[0];
            iTestResult.setAttribute("failed_case", tCase);
        }
    
        @Override
        public void onTestSuccess(ITestResult iTestResult) {
            super.onTestSuccess(iTestResult);
            TestCase tCase = (TestCase) iTestResult.getParameters()[0];
            iTestResult.setAttribute("passed_case", tCase);
        }
    
        @Override
        public void onTestSkipped(ITestResult iTestResult) {
            super.onTestSkipped(iTestResult);
            TestCase tCase = (TestCase) iTestResult.getParameters()[0];
            iTestResult.setAttribute("skipped_case", tCase);
        }
      }
    

    In my custom report class, I get the objects of every test case like below:

            TestCase failedCase = (TestCase) testResult.getAttribute("failed_case");
            TestCase passedCase = (TestCase) testResult.getAttribute("passed_case");
            TestCase skippedCase = (TestCase) testResult.getAttribute("skipped_case");