mahan
mahan

Reputation: 14935

testng - Get name of the class that contains failed test

<test name="Test">
   <classes>
     <class name="io.test.FirstTest"/>
   </classes>
</test>

I want to get name of the FirsTest class without the package name inside onTestFailure. In other wors, I need to get FirstTest, not io.test.FirstTest. How to do so?

   public class TestListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult testResult) {

    }
  }

I have used testResult.getInstanceName(), but it returns io.test.FirstTest. Therefore, I have used string.substring():

   final String name = testResult.getInstanceName();
   final String result = name.substring(navn.lastIndexOf(".") + 1).trim();

But is there a better solution?

Upvotes: 0

Views: 517

Answers (1)

Alexey R.
Alexey R.

Reputation: 8676

Try this approach:

package click.webelement.testng;

import org.testng.Assert;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners({TListenerTest.class})
public class TListenerTest implements ITestListener {

    @Test
    public void toFail(){
        Assert.assertTrue(false);
    }

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println(result.getInstance().getClass().getSimpleName());
        System.out.println(result.getTestClass().getClass().getSimpleName());
    }
}

However I would not rely on the "simple names". They look nice unless you run into dups sooner or later (since you wouldn't be able to distinguish classes with the same name but from different packages).

Upvotes: 2

Related Questions