【问题标题】:How do I test a list in a JUnit test?如何在 JUnit 测试中测试列表?
【发布时间】:2012-05-26 22:38:36
【问题描述】:

我创建了一个 Survey.java 类和一个 SurveyTest.java JUnit 测试。但我不确定如何在调查类中测试列表。如何在 JUnit 测试中测试它们?

Survey.java

package com.jhaksurvey.model;

import java.util.List;

public class Survey {

private long id;
private String title;
private boolean active = true;
private List<Question> questions;

public Survey() {

}

public Survey(long id, String title) {
this.id=id;
this.title=title;   
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public boolean isActive() {
return active;
}

public void setActive(boolean active) {
this.active = active;
}

public List<Question> getQuestions() {
return questions;
}

public void setQuestions(List<Question> questions) {
this.questions = questions;
}

}

SurveyTest.java

package com.survey.model.test;

import junit.framework.Assert;
import junit.framework.TestCase;

import com.survey.model.Survey;


public class SurveyTest extends TestCase {

private Survey survey;

protected void setUp() throws Exception {
    super.setUp();  
    survey = new Survey();
}

public void testSurvey() {
    survey.toString();
}

public void testSurveyLongString() {
    fail("Not yet implemented");
}

public void testGetId() {
    long expected = (long) Math.random();
    survey.setId(expected);
    long actual = survey.getId();
    Assert.assertEquals(expected, actual);
}

public void testGetTitle() {
    String expected = "surveytitle";
    survey.setTitle(expected);
    String actual = survey.getTitle();
    Assert.assertEquals(expected, actual);  
}

public void testIsActive() {
    Boolean expected = true;
    survey.setActive(expected);
    Boolean actual = survey.isActive();
    Assert.assertEquals(expected, actual);
}

public void testGetQuestions() {
    fail("Not yet implemented");
}

}

【问题讨论】:

  • 您基本上是在测试 setter 和 getter 是否正常工作 - 在您的情况下,这些非常简单,因此没有附加价值。您正在测试 Java 和 JVM(变量赋值/读取)的基础知识,这很臃肿。如果您将一些相关的业务逻辑添加到您的类中,则适合对其进行测试。测试 setter 和 getter 仅适用于人为增加代码覆盖率指标。

标签: java eclipse list testing junit


【解决方案1】:

那个类没有真正的逻辑,所以你不需要测试这个类。您应该只测试包含某种逻辑的类。

【讨论】:

    【解决方案2】:

    Survey.java 是一个隐藏值的模型/数据结构。理想情况下,您应该测试使用调查类的类。例如。 CreateSurvey 可能是创建调查的类,因此您可以对 create 方法进行单元测试,以确保它正确设置调查对象的值。

    【讨论】:

      【解决方案3】:

      你可以测试列表是否为空

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多