Deadmin1
Deadmin1

Reputation: 63

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.

Upvotes: 5

Views: 8403

Answers (1)

Marcus K.
Marcus K.

Reputation: 1040

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.

Upvotes: 12

Related Questions