【问题标题】:JUnit Branch CoverageJUnit 分支覆盖
【发布时间】:2018-05-16 18:19:53
【问题描述】:

当我运行这个 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());
}

【问题讨论】:

标签: java junit4


【解决方案1】:

添加这些额外的测试来验证边缘用例会将 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();
}

【讨论】:

    【解决方案2】:

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

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

    所有这些都是错误的,所有这些都是正确的,并且介于两者之间。分支检查器不明白

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多