Issue
@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?
Solution
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);}
Answered By - C.B.