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.
您需要在调用其上的方法之前初始化entries
:
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?
您的Stack
类需要将条目初始化为空列表:
private List<Entry> entries = new ArrayList<>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.