问题
@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());
}
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?
回答1:
created a private field in your test class outside your test setup, i.e.
public class MyTest{
private Ground ground;
...
}
Then instantiate ground in your before()
@Before
public void before(){ground = new Ground(100,100);}
回答2:
I had faced this issue when instead of org.junit.Test I had imported org.junit.jupiter.api.Test
回答3:
Agreeing with @ANU JOHN, the following imports didn't match up:
import org.junit.Before;
import org.junit.jupiter.api.Test;
Changing the second to org.junit.Test; fixed it for me.
来源:https://stackoverflow.com/questions/21612890/junit-before-not-working-properly