Java JUnit测试不适用于@Before注释 [英] Java JUnit testing not working with @Before annotation
问题描述
Heay com,
从Java JUnit测试开始,并遇到了有关@Before注释的问题.
started with Java JUnit testing and got a problem regarding @Before annotation.
我的设置: Java 9 蚀氧 JUnit 5
My setup: Java 9 Eclipse Oxygen JUnit 5
如果我像这样进行测试
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));
}
}
测试将运行正常.但是,如果我在@Before注释中执行XY对象,则它将以错误结尾.断言行中的Nullpointer.
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));
}
}
谢谢.
推荐答案
与 JUnit 5手册状态,必须使用@BeforeEach
.旧的@Before
注释仅适用于版本4:
As the JUnit 5 manual states, you must use @BeforeEach
. The old @Before
annotation only works with version 4:
@BeforeEach
-表示带注释的方法应在当前类中的每个@Test
[...]之前执行;类似于JUnit 4的@Before
.
@BeforeEach
- Denotes that the annotated method should be executed before each@Test
[...] in the current class; analogous to JUnit 4’s@Before
.
这篇关于Java JUnit测试不适用于@Before注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!