2013-10-22 159 views
0

我得到一个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; 
    } 

感谢。

+0

您需要首先为每个测试呼叫设置方法,或者如下所述,通过设置此字段创建@Before方法。因为每个测试都不依赖于另一个测试,所以你的学生最初是空的,你没有设置它 - 所以你有空。 – lummycoder

+0

没有堆栈跟踪的NPE问题。 – Raedwald

回答

4

你需要使用它

你可以做到这一点无论是在一个@Before方法或test itself内之前初始化你的主要对象。

OPTION 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()); 
} 

OPTION 2

创建@Before方法,使用@Before主呸时在执行任何@Test之前LD将被创建,还有另一种选择,选项3,使用@BeforeClass

​​

OPTION 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. 
} 
+0

谢谢..我正在寻找@Before(选项2) – Hash

3

每个测试方法得到的MainTest一个新实例。这意味着您在第一种方法中所做的更改不会显示在第二种方法中,等等。一种测试方法与另一种测试方法之间没有顺序关系。

您需要让每个方法成为一个自包含的测试,用于测试课程行为的一个方面。