Value of a ThreadLocal get is always null inside a ITestListener when run through testng.xml with parallel enabled

319 views
Skip to first unread message

prvn

unread,
Mar 11, 2018, 11:15:17 PM3/11/18
to testng-users
I have the following classes.

public class CoreClass {


    private static ThreadLocal<String> threadLocalString = new ThreadLocal<String>();


    public static String getThreadLocalString() {

        return threadLocalString.get();

    }


    public static void setThreadLocalString(String value) {

        threadLocalString.set(value);

    }

}


@Listeners(com.java.testng.play.TestListener.class)

public class TestClass {


    @Test

    public void testClassMethod() {

        CoreClass.setThreadLocalString("newTest....");

        System.out.println(CoreClass.getThreadLocalString());

    }


}



public class TestListener implements ITestListener {


    public void onTestStart(ITestResult result) {

        // TODO Auto-generated method stub


    }


    public void onTestSuccess(ITestResult result) {

        // TODO Auto-generated method stub


    }


    public void onTestFailure(ITestResult result) {

        // TODO Auto-generated method stub


    }


    public void onTestSkipped(ITestResult result) {

        // TODO Auto-generated method stub


    }


    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {

        // TODO Auto-generated method stub


    }


    public void onStart(ITestContext context) {

        // TODO Auto-generated method stub


    }


    public void onFinish(ITestContext context) {

        System.out.println("Value:::: " + CoreClass.getThreadLocalString());

    }


}



<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite thread-count="2" name="Suite" parallel="classes">

  <test name="Test">

    <classes>

      <class name="com.java.testng.play.TestClass"/>

    </classes>

  </test> <!-- Test -->

</suite> <!-- Suite -->



Now if I run this testng.xml everything works fine except the "onFinish" method. The system out always returns null. But when I run the test individually without testng.xml or when I don't run tests in parallel by enabling it in testng.xml it works fine. The system.out results value normally. Why is this happening?

Reply all
Reply to author
Forward
0 new messages