英文:
Why TestNG's beforeSuite only provides a value for one class while the other class 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);
}
}
testng.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>
测试结果:
mvn clean test
.
.
.
[INFO] Running TestSuite
B name:null
A name:stackoverflow
你提到你的 TestNG 版本是 6.8.8。
英文:
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.
答案1
得分: 1
问题出在测试代码中。您有一个常见的基类,多个子类扩展了该基类,并且在基类中有一个 @BeforeSuite
方法。
根据 TestNG 的行为,它保证 @BeforeSuite
方法仅在每个 <suite>
标签中执行一次。
在您的情况下,它已经为类 A
调用过,因此在类 B
中将被跳过,这解释了 NullPointerException
的原因。
要解决这个问题,您需要将初始化操作移到 @BeforeMethod
或 @BeforeClass
注解的方法中。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论