繁体   English   中英

在setter和getter上进行JUnit测试失败

[英]JUnit test on setters and getters failing

当我在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和getters在Main类中

主要

public String getStudent() {
        return student;
    }


public void setStudent(final String studentIn) {
        this.student = studentIn;
    }

谢谢。

您需要在使用之前初始化主对象

您可以在@Before方法上或在test itself

选项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.
}

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

您需要使每个方法成为一个独立的测试,以测试类行为的一个方面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM