我得到一个nullpointerexception当我在eclipse中运行junit测试。我在这里错过了什么?JUnit测试setter和getters失败
MainTest
public class MainTest {
private Main main;
@Test
public void testMain() {
final Main main = new Main();
main.setStudent("James");
}
@Test
public void testGetStudent() {
assertEquals("Test getStudent ", "student", main.getStudent());
}
@Test
public void testSetStudent() {
main.setStudent("newStudent");
assertEquals("Test setStudent", "newStudent", main.getStudent());
}
}
getter和setter方法是在主类
主要
public String getStudent() {
return student;
}
public void setStudent(final String studentIn) {
this.student = studentIn;
}
感谢。
您需要首先为每个测试呼叫设置方法,或者如下所述,通过设置此字段创建@Before方法。因为每个测试都不依赖于另一个测试,所以你的学生最初是空的,你没有设置它 - 所以你有空。 – lummycoder
没有堆栈跟踪的NPE问题。 – Raedwald