I am trying to get the stored String Object in ThreadLocal in my BaseClass to the TestClass. In the following code I have defined the ThreadLocal and stored a String by set() method. But when I try to get that stored string in my TestClass that extends BaseClass it becomes null. What am I missing here?
My BaseClass code is as follows:
package base;
import org.testng.annotations.BeforeSuite;
public class BaseClass {
private static final ThreadLocal<String> str = new ThreadLocal<>();
public void setString(String string){
str.set(string);
}
public static String getString(){
return str.get();
}
@BeforeSuite
public void setDesiredString(){
String desiredString = "I am a String.";
setString(desiredString);
}
}
And my TestClass code is as follows:
package tests;
import base.BaseClass;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestClass extends BaseClass {
String str = getString();
@Test
public void TestString() {
Assert.assertEquals(str,"I am a String." );
}
}
When I run the TestClass, I get the following output:
java.lang.AssertionError:
Expected :I am a String.
Actual :null
I am expecting to have a passed test having same Expected & Actual string that was stored in the ThreadLocal in BaseClass via setDesiredString() which is "I am a String."