JUnit分支机构覆盖范围

时间:2017-12-02 23:44:12

标签: java junit4

运行此JUnit测试时,我获得了1/4分支覆盖率。但是,当我将if语句更改为" if(points == 1 || points == 2 || points == 3 || points == 4)"它通过了JUnit测试。我做错了什么?

主要课程:

public int getPoints() {
    return points;
}

public Grade(int p) throws IllegalArgumentException {
    if (p < 1 || p > 20)
        throw new IllegalArgumentException();
    points = p;
}

// Your additions/changes below this line

public Classification classify() {

    if (points >= 1 && points <= 4) {
        return Classification.First;
    }
    else {
        throw new IllegalArgumentException("Not a Grade");
    }
}

JUnit测试:

 @Test
 public void testFirst() {
    Assert.assertEquals(Classification.First, new Grade(1).classify());
    Assert.assertEquals(Classification.First, new Grade(2).classify());
    Assert.assertEquals(Classification.First, new Grade(3).classify());
    Assert.assertEquals(Classification.First, new Grade(4).classify());
}

2 个答案:

答案 0 :(得分:1)

这样的条件有16个可能的分支:

(a == 1 || b == 1 || c == 1 || d == 1)

所有这些都是假的,所有这些都是真的,而且都介于两者之间。分支检查员不理解

(points == 1 || points == 2 || points == 3 || points == 4)

只有5个分支,因为它不分析条件之间的关系。

答案 1 :(得分:0)

添加这些额外的测试以验证边缘情况将使constructorclassify方法的JUnit覆盖率增加到4/4,代价是制作一堆(可能)毫无价值的测试用例,并且还打破了数据封装(因为您在每种方法中都有重复的验证检查)。

@Test(expected = IllegalArgumentException.class)
public void TestSecond()
{
    new Grade(0).classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestThird()
{
    new Grade(5).classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestFourth()
{
    final Grade g = new Grade(1);
    g.points = 0;
    g.classify();
}

@Test(expected = IllegalArgumentException.class)
public void TestFifth()
{
    final Grade g = new Grade(1);
    g.points = 5;
    g.classify();
}