I am using TestNG as my Java testing framework, and I have the need for a given test class to maintain some state which will be used by several of the test methods. Specifically, I would like this state to be initialized once, before any tests are run, but then have it be available to any subsequent test in the class.
From what I read, the @BeforeClass
annotation can be added to a method, which will run before any tests are run. However, I have been noticing very strange behavior. Consider the following sample code, which is a distilled version of my actual setup:
public class MyTestClass {
private static String[][] array;
@BeforeClass
public void setup() {
array = new String[][] {{"A", "B", "C"},{"D", "E", "F"},{"G", "H", "I"}};
}
@Test
public void someTest() {
// use 'array'
// but the data might be corrupted
}
}
The above is a simplification, but what I have noticed is that static
variables which I initialize in the @BeforeClass
method appear to be having their values changed later on.
What is the proper way of setting up some shared/static state for a TestNG unit test?
答案 0 :(得分:1)
Unittest methods should not depend on each other in any way and therefor should not share any state!
答案 1 :(得分:0)
A static variable may be initialized multiple times depending on your setup. You could initialize using a static initializor instead, or remove the static keyword and use it as an instance variable of the class using the existing configuration:
Example :
public class MyTestClass {
private static String[][] array;
static {
array = new String[][] {{"A", "B", "C"},{"D", "E", "F"},{"G", "H", "I"}};
}
@Test
public void someTest() {
// use 'array'
// but the data might be corrupted
}
}
Or,
public class MyTestClass {
private String[][] array;
@BeforeClass
public void setup() {
array = new String[][] {{"A", "B", "C"},{"D", "E", "F"},{"G", "H", "I"}};
}
@Test
public void someTest() {
// use 'array'
// but the data might be corrupted
}
}
答案 2 :(得分:0)
您可以在声明中使用 final 关键字。
你也可以使用 ITestContext 这里是一个问题http://www.ontestautomation.com/using-the-testng-itestcontext-to-create-smarter-rest-assured-tests/
public class MyTestClass {
private static final String[][] array;
@BeforeClass
public void setup() {
array = new String[][] {{"A", "B", "C"},{"D", "E", "F"},{"G", "H", "I"}};
}
@Test
public void someTest() {
// use 'array'
// but the data might be corrupted
}
}