简体   繁体   English

JUnit分支范围

[英]JUnit Branch Coverage

I am getting 1/4 branch coverage when I run this JUnit test. 运行此JUnit测试时,我得到了1/4的分支覆盖率。 However, when I change the if statement to "if (points == 1 || points == 2 || points == 3 || points == 4)" it passes the JUnit test. 但是,当我将if语句更改为“ if(点== 1 ||点== 2 ||点== 3 ||点== 4)”时,它将通过JUnit测试。 What am I doing wrong? 我究竟做错了什么?

Main class: 主班:

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: 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());
}

A condition like this has 16 possible branches: 这样的条件有16个可能的分支:

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

with all of them false, all of them true, and all in between. 所有这些都是假的,所有都是真实的,并且介于两者之间。 The branch checker does not understand that 分支检查器不明白

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

has only 5 branches, because it does not analyze the relationship between the conditions. 只有5个分支,因为它不分析条件之间的关系。

Adding these additional tests to verify edge cases will increase your JUnit coverage to 4/4 for both the constructor and classify methods, at the cost of making a bunch of (possibly) worthless test cases, and also breaking data encapsulation (since you have duplicate validation checks in each of these methods). 添加这些额外的测试以验证边缘情况将使constructor方法和classify方法的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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM