简体   繁体   中英

Java JUnit testing not working with @Before annotation

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.

As the JUnit 5 manual states, you must use @BeforeEach . The old @Before annotation 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM