简体   繁体   English

JUnit NullPointerException

[英]JUnit NullPointerException

I am getting a NullPointerException when trying to test a method in a class with a special type. 尝试在具有特殊类型的类中测试方法时,我收到NullPointerException。 I am our of ideas as to the reason for this exception. 我是关于这个例外的原因的想法。

public class TestStack {
    private Stack st;
    private Entry en;
    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        st = new Stack();
        en = new Entry(1);
    }

    @Test
    public void pushThenTop() {
        st.push(en);
        assertEquals("TEST1: push then Top", 1, st.top());
        fail("Incorrect type");
    }

}

Stack Class 堆栈类

public class Stack {
    private int size;
    private List<Entry> entries;
    public void push(Entry i) {
        entries.add(i);
    }

    public final Entry pop() throws EmptyStackException {
        if (entries.size() == 0) {
            throw new EmptyStackException();
        }
        Entry i = entries.get(entries.size() - 1);
        entries.remove(entries.size() - 1);
        return i;
    }

    public Entry top() throws EmptyStackException {
        return entries.get(entries.size() -1);
    }

    public int size() {
        size = entries.size();
        return size;
    }
}

I am trying to run a test that returns the value of the element in the list. 我正在尝试运行一个测试,返回列表中元素的值。

您需要在调用其上的方法之前初始化entries

entries = new ArrayList<Entry>();

You are getting an NPE because you have a bug in your code. 您正在获得NPE,因为您的代码中存在错误。 This is the sort of thing a unit test should be finding so I suggest you fix the bug. 这是单元测试应该找到的东西,所以我建议你修复bug。 You have to set entries to something and if you don't you should expect to get an NPE. 你必须设置entries ,如果你不设置,你应该期望获得NPE。

I am our of ideas as to the reason for this exception. 我是关于这个例外的原因的想法。

This is where you need to look at the line where the exception is thrown and ask yourself is there any value used which could be null or a reference not set? 这是您需要查看抛出异常的行的位置,并且问自己是否使用了可能为null或未设置引用的值?

您的Stack类需要将条目初始化为空列表:

private List<Entry> entries = new ArrayList<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM