【问题标题】:Junit - Null Pointer Exception with @BeforeJunit - @Before 的空指针异常
【发布时间】:2018-03-07 21:30:09
【问题描述】:

我刚开始学习 Junit,但在我的第一次测试中我刚刚得到了 Null Pointer Exception。

如果我阅读正确@Before 注释意味着它将在每次测试之前被调用,但看起来它没有或此代码有其他问题。在下面的这段代码中,我在myList.add() 行中得到了空指针。

import org.junit.Before;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class StudentTest {
    private List<String> myList;

    @Before
    public void init(){
        myList = new ArrayList<>();
    }
    @Test
    public void size(){
        myList.add("TEST");
        assertEquals(1, myList.size());
    }
}

【问题讨论】:

  • 它在我的 IDE 中工作。您应该将其作为 JUnit Test 运行

标签: junit nullpointerexception


【解决方案1】:

导入(jupiter)表明您正在使用 Junit5。 在 JUnit5 中,您必须使用 @BeforeEach 注释来指示必须在每个测试方法之前执行的步骤。

@Before 注解在 JUnit4 中使用。

这个我没测试过,看文档https://junit.org/junit5/docs/current/user-guide/

【讨论】:

  • 你是对的,它与@BeforeEach 一起工作。看起来我导入了错误的 JUnit。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 2021-06-15
  • 1970-01-01
  • 2018-08-27
  • 2016-08-19
  • 1970-01-01
相关资源
最近更新 更多