Java JUnit测试不适用于@Before注释 [英] Java JUnit testing not working with @Before annotation

查看:218
本文介绍了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 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 @Beforeannotation 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆