如何为返回带参数的新对象的方法编写junit测试用例

时间:2016-04-04 20:15:59

标签: java junit

我是JUnit测试的新手。我正在尝试为getRequest()方法编写测试用例,该方法返回带参数的对象。

class Test(  
    public Student getRequest(){
    return new Student(id, name, section);
    }
    }

    public class Student{
    private String id;
    private String name;
    private String section;

    public Student(String id, String name, String section){
    this.id=id;
    this.name=name;
    this.section=section;
    }
    }

1 个答案:

答案 0 :(得分:1)

抱歉,我发现这令人困惑。您编写JUnit类来练习您要测试的类的方法。您不必在测试类中编写任何您想要的旧方法。

这是您要测试的课程:

public class Student {
    private String id;
    private String name;
    private String section;

    public Student(String id, String name, String section) {
        this.id=id;
        this.name=name;
        this.section=section;
    }

    // Note: You'll need getters.
}

我开始用这种方式编写JUnit类:

public class StudentTest { 

    @Test 
    public void testStudent_Constructor() {
        String testId = "1";
        String testName = "Foo Bar";
        String testSection = "123";

        Student student = new Student(testId, testName, testSection);    
        Assert.assertNotNull(student);
        Assert.assertEquals(testId, student.getId());
        Assert.assertEquals(testName, student.getName());
        Assert.assertEquals(testSection, student.getSection());
    }
}