Junit @之前无法正常工作 [英] Junit @Before not working properly
问题描述
@Before
public void setup(){
Ground ground = new Ground(100, 100);
}
@Test
public void getDimX(){
String msg = "For a newly created Ground(100, 100), ground.getDimensionX() should return 100";
assertEquals(100, ground.getDimensionX());
}
上面的代码返回一个NullPointerException.如果将Ground ground = new Ground(4, 4);
移到getDimX()
方法中,则测试运行正常.我有很多使用相同基础的测试,所以我不希望每个测试用例都做一个新的测试.另外,如果我完全摆脱了@Begin
块,而只保留了地面实例化,它也可以正常工作.那么@Before?
The above code returns a NullPointerException. If I move the Ground ground = new Ground(4, 4);
into the getDimX()
method, the test runs just fine. I have a number of tests that will use the same ground, so I would prefer not to make a new one with each test case. Also, if I get rid of the @Begin
block entirely and just leave the ground instantiation, it also works fine. What then is the point of the @Before?
推荐答案
在测试设置之外的测试类中创建了一个私有字段,即
created a private field in your test class outside your test setup, i.e.
public class MyTest{
private Ground ground;
...
}
然后在before()
@Before
public void before(){ground = new Ground(100,100);}
这篇关于Junit @之前无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!