Search code examples
testngintegration-testingjunit5testng-dataprovider

Clearing overridden testContext values after a test


I extended TestListenerAdapter and added my own custom testName values. This is specifically for the use-cases where I have a data provider and I am using the dataprovider values to set the name.

Here is how the listener looks like:

public class CustomListener extends TestListenerAdapter {

    @Override
    public void onTestSuccess(final ITestResult tr) {
        setTestNameInReport(tr);
        super.onTestSuccess(tr);
    }

    @Override
    public void onTestFailure(final ITestResult tr) {
        setTestNameInReport(tr);
        super.onTestSuccess(tr);
    }

    private void setTestNameInReport(final ITestResult tr) {
        try {
            ITestContext ctx = tr.getTestContext();
            Set<String> attributes = ctx.getAttributeNames();
            for ( String x : attributes ) {
                if (x.contains("testName")) {
                    Field method = TestResult.class.getDeclaredField("m_method");
                    System.out.println("Printing the method name: " + method.getName());
                    method.setAccessible(true);
                    method.set(tr, tr.getMethod().clone());
                    Field methodName = BaseTestMethod.class.getDeclaredField("m_methodName");
                    methodName.setAccessible(true);
                    methodName.set(tr.getMethod(), ctx.getAttribute( x ));
                    break;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}

I am setting the testName in the test case.

However, there are few cases which don't have a data provider and don't need any custom test name, how do I clear the test context values?


Solution

  • You can use removeAttribute() method of your ITestContext. So that the code would look like:

    @AfterMethod()
    public void clearContext(ITestContext context){
        context.removeAttribute("testName");
    }