Java JUnit testing not working with @Before annotation

南楼画角 提交于 2021-02-10 18:42:12

问题


Heay com,

started with Java JUnit testing and got a problem regarding @Before annotation.

My setup: Java 9 Eclipse Oxygen JUnit 5

If i do my test like this

package junittesting;


import org.junit.jupiter.api.Test;
import de.hsa.games.fatsquirrel.space.XY;

public class XYtest {
    private XY testXY = new XY(0,0);
    private XY addingVec = new XY(0,1);


    @Test
    public void addVec() {

        assert (testXY.addVec(addingVec).equals(addingVec));
    }

}

the test will run fine. But if i do my XY objects in the @Before annotation then it will end with an error. Nullpointer in the assert line.

    package junittesting;

import org.junit.Before;
import org.junit.jupiter.api.Test;
import de.hsa.games.fatsquirrel.space.XY;

public class XYtest {

    XY testXY;
    XY addingVec;

    @Before
    public void setUp() {
        testXY = new XY(0, 0);
        addingVec = new XY(0, 1);
    }

    @Test
    public void addVec() {

        assert (testXY.addVec(addingVec).equals(addingVec));
    }


}

Thanks in advance.


回答1:


As the JUnit 5 manual states, you must use @BeforeEach. The old @Beforeannotation only works with version 4:

@BeforeEach - Denotes that the annotated method should be executed before each @Test [...] in the current class; analogous to JUnit 4’s @Before.



来源:https://stackoverflow.com/questions/50667407/java-junit-testing-not-working-with-before-annotation

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