JUnit 理论将 params 设置为 null
JUnit theories sets params to null
我有一个测试 class 使用这样的理论:
@RunWith(Theories.class)
public class XTest(){
public static X x1;
public static X x2;
@DataPoints("xlist")
public static X[] xList = {x1, x2};
}
@Before
public void setUp() throws Exception {
x1 = new X();
x2 = new X();
}
@Theory
public void test(@FromDataPoints("xlist" x){
// x is null
}
我不明白为什么 x
为空。我对参数化测试进行了相同的尝试,但仍然为空。我在这里错过了什么?
您的代码中的问题来自 "init" 订单。
xList 是 static;因此,当您的测试 class 第一次被 加载 时,会执行初始化代码。此时,x1 和 x2 这两个字段仍处于 null - 因为 @Before 方法将 运行 later .
所以,这里一个简单的解决方法是根本不使用@Before,而是使用:
public static X x1 = new X();
相反。
我认为你应该改变你的 class 的结构以使其工作,因为我对理论的了解,这将是正确的结构:
@RunWith(Theories.class)
public class TheoryTest {
@DataPoints("xlist")
public static Integer[] xList = new Integer[] {new Integer(1), new Integer(2), new Integer(45)};
@Theory
public void singleTest(@FromDataPoints("xlist") Integer x){
// x is null
System.out.println("Size " +x);
}
}
要做的是为数组 "xlist" 中的每个值调用您的方法 "singleTest" 一次,因此将使用值
调用 3 次
xList = 1
xList = 2
xList = 45
您不需要声明单个变量 x1,x2。
我有一个测试 class 使用这样的理论:
@RunWith(Theories.class)
public class XTest(){
public static X x1;
public static X x2;
@DataPoints("xlist")
public static X[] xList = {x1, x2};
}
@Before
public void setUp() throws Exception {
x1 = new X();
x2 = new X();
}
@Theory
public void test(@FromDataPoints("xlist" x){
// x is null
}
我不明白为什么 x
为空。我对参数化测试进行了相同的尝试,但仍然为空。我在这里错过了什么?
您的代码中的问题来自 "init" 订单。
xList 是 static;因此,当您的测试 class 第一次被 加载 时,会执行初始化代码。此时,x1 和 x2 这两个字段仍处于 null - 因为 @Before 方法将 运行 later .
所以,这里一个简单的解决方法是根本不使用@Before,而是使用:
public static X x1 = new X();
相反。
我认为你应该改变你的 class 的结构以使其工作,因为我对理论的了解,这将是正确的结构:
@RunWith(Theories.class)
public class TheoryTest {
@DataPoints("xlist")
public static Integer[] xList = new Integer[] {new Integer(1), new Integer(2), new Integer(45)};
@Theory
public void singleTest(@FromDataPoints("xlist") Integer x){
// x is null
System.out.println("Size " +x);
}
}
要做的是为数组 "xlist" 中的每个值调用您的方法 "singleTest" 一次,因此将使用值
调用 3 次xList = 1
xList = 2
xList = 45
您不需要声明单个变量 x1,x2。