java - 对 setter 和 getter 的 JUnit 测试失败

标签 java eclipse unit-testing junit junit4

当我在 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/

相关文章:

android - Git 用于控制 Android 项目的版本

html - 无法使用tomcat服务器在eclipse中导航html文件

angular - NgRx 测试 - 检查分派(dispatch) Action 的顺序

java - 打印 2 到 500 之间的素数

java - 如何从 IntelliJ IDEA 中使用 Gradle 运行主要方法?

Eclipse 3.7 (Indigo) + Tomcat7 --- 无法使用所选类型创建服务器

c# - 单元测试抛出异常但看不到消息

c# - FluentAssertions 断言已为重载运算符抛出异常

Java Unicode 到十六进制字符串

java - 这个键绑定(bind)有什么问题?