Junit @Before not working properly

只愿长相守 提交于 2021-01-28 04:30:52

问题


@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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!