Question

I am getting a NullPointerException when trying to test a method in a class with a special type. 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.

Was it helpful?

Solution 3

Your Stack class needs to initialize entries to an empty list:

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

OTHER TIPS

You need to initialize entries before invoking a method on it:

entries = new ArrayList<Entry>();

You are getting an NPE because you have a bug in your code. This is the sort of thing a unit test should be finding so I suggest you fix the bug. You have to set entries to something and if you don't you should expect to get an 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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top