如何为类编写JUnit测试用例

时间:2015-10-20 16:43:54

标签: java junit

我是一个更新鲜的人,我需要知道如何为这个类编写 JUnit 测试用例。任何人都可以帮助我吗?

package com.jpmc.cb.creos.util.grid;

public class GridHelper {

    public static List<GridFilter> getGridFilters(String jsonFilters)throws JsonParseException, JsonMappingException, IOException
    {
        List<GridFilter> filters = new ArrayList<GridFilter>();
        GridFilter filter[] = new ObjectMapper().readValue(jsonFilters,
                GridFilter[].class);
        for (int i = 0; i < filter.length; i++) {
            filters.add(filter[i]);
        }
        return filters;
    }
}

这是GridFilter类:

package com.jpmc.cb.creos.util.grid;

public class GridFilter {

private String property;
private String value;
private String operator;

public GridFilter() {}

public GridFilter(String property, String operator, String value)
{
    this.property = property;
    this.value = value;
    this.operator = operator;
}

public String getProperty() {
    return property;
}

public void setProperty(String property) {
    this.property = property;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public String getOperator() {
    return operator;
}

public void setOperator(String operator) {
    this.operator = operator;
}

}

1 个答案:

答案 0 :(得分:2)

以下是测试内容的一些想法。为(至少)以下情况编写测试方法:

  • 带有2个过滤器的格式良好的json应该返回一个列表,其中包含两个匹配值为
  • 的过滤器
  • 没有过滤器的格式良好的json应该返回一个空列表
  • 格式错误的json应该引发JsonParseException
  • 其他不良数据引发其他异常类型

如何编写测试用例?不清楚你在问什么。但这是一个例子:

@Test
public void empty_json_gives_empty_list() throws Exception {
    assertEquals(Collections.emptyList(), GridHelper.getGridFilters("[]"));
}
相关问题