当我在 Eclipse 中运行 junit 测试时,出现nullpointerException。我在这里缺少什么?
主要测试
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());
}
}
setter 和 getter 位于 Main 类中
主要
public String getStudent() {
return student;
}
public void setStudent(final String studentIn) {
this.student = studentIn;
}
谢谢。
最佳答案
在使用主对象之前需要初始化它
您可以在 @Before
方法上或在测试本身
内执行此操作。
选项 1
改变
@Test
public void testSetStudent() {
main.setStudent("newStudent");
assertEquals("Test setStudent", "newStudent", main.getStudent());
}
至
@Test
public void testSetStudent() {
main = new Main();
main.setStudent("newStudent");
assertEquals("Test setStudent", "newStudent", main.getStudent());
}
选项 2
创建一个@Before方法,当使用@Before时,主字段将在执行任何@Test之前创建,还有另一个选项,选项3,使用@BeforeClass
@Before
public void before(){
main = new Main();
}
选项 3
@BeforeClass
public static void beforeClass(){
//Here is not useful to create the main field, here is the moment to initialize
//another kind of resources.
}
关于java - 对 setter 和 getter 的 JUnit 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19515909/