问题
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 @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
.
来源:https://stackoverflow.com/questions/50667407/java-junit-testing-not-working-with-before-annotation