I have a problem with the BeforeSuite
annotation in TestNG.
I want to initialize some variables in beforeSuite()
so all the classes could use them directly. Only class A can get the value. Class B can't; it gets null.
Base.java:
public class Base {
public String name;
@BeforeSuite
public void beforeSuite(){
name = "stackoverflow";
}
}
A.java:
public class A extends Base{
@Test
public void test(){
System.out.println("A name:" + name);
}
}
B.java
public class B extends Base{
@Test
public void test(){
System.out.println("B name:" + name);
}
}
textng.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="suite1" parallel="classes" thread-count="1" preserve-order="true">
<test name="testValue">
<classes>
<class name="A"/>
<class name="B"/>
</classes>
</test>
</suite>
test result:
mvn clean test
.
.
.
[INFO] Running TestSuite
B name:null
A name:stackoverflow
My TestNG version is 6.8.8.
The problem lies in the test code. You have a common base class that is being extended by multiple child classes and within the base class you have a @BeforeSuite
method.
TestNG by behavior, guarantees that the @BeforeSuite
method gets executed ONLY once per <suite>
tag.
In your case, it already got invoked for class A
and so it will be skipped for class B
which explains the NullPointerException
.
To fix this, you would need to move your initialization to either a @BeforeMethod
or @BeforeClass
annotated method.