本文介绍了Java JUnit测试不适用于@Before注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Heay com,

从Java JUnit测试开始,并遇到了有关@Before注释的问题.

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

我的设置:Java 9蚀氧JUnit 5

My setup:Java 9Eclipse OxygenJUnit 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 @Beforeannotation only works with version 4:

这篇关于Java JUnit测试不适用于@Before注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 23:45