天天看點

Cobertura計算覆寫率使用Cobertura計算代碼覆寫率

使用Cobertura計算代碼覆寫率

軟體測試過程中需要計算代碼覆寫率,使用cobertura過程中對于這個工具的計算結果感到疑惑,于是自己動手實踐了一下。

使用到的demo例子來源此部落格

部落格連結

demo連結

把pom.xml中的注釋打開

Cobertura計算覆寫率使用Cobertura計算代碼覆寫率

修改了一下demo的HelloWorld.java與HelloWorldTest.java。

package com.test.jacoco;

public class HelloWorld {
    public HelloWorld() {
    }

    public String sayHi() {
        return "Hello World";
    }

    public int minusNum(int a, int b)
    {
        if (a < b)
        {
            int c = b - a;
            System.out.println(c);
            return c;
        }
        else if (a==b) {
            return 0;
        }
        else
        {
            return a - b;
        }
    }

    public int addNum(int a, int b) {
        if (a > b) {
            int c = 5;
            System.out.print(c);
        }
        else if (a == b)
        {
            int c = 6;
            System.out.println(c);
        }
        /*
        * word
        * word
        *
        *
        * */
        else
        {
            /*
             * a
             * b
             * c
             *
             * */
            int c = 7;
            System.out.println(c);
        }
        return a + b;
    }
}

           
package com.test.jacoco.test;

import junit.framework.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.test.jacoco.HelloWorld;

public class HelloWorldTest {
    @Test
    public void testMethod1() {
        HelloWorld hw = new HelloWorld();
        String word = hw.sayHi();
        assertEquals(word, "Hello World");
    }

    @Test
    public void testMethod2() {
        HelloWorld hw = new HelloWorld();
        int num = hw.addNum(1, 3);
        assertEquals(num, 4);
    }

    @Test
    public void testMethod3() {
        HelloWorld hw = new HelloWorld();
        int num = hw.addNum(1, 1);
        assertEquals(num, 2);

    }

    @Test
    public void testMethod4() {
        HelloWorld hw = new HelloWorld();
        int num = hw.addNum(3, 1);
        assertEquals(num, 4);

    }

    @Test
    public void testMethod5() {
        HelloWorld hw = new HelloWorld();
        int num = hw.minusNum(3, 1);
        assertEquals(num, 2);

    }

}

           

在項目根目錄輸入

mvn cobertura:cobertura
           

然後在 ~/target/site/cobertura中打開index.html

整體結果

Cobertura計算覆寫率使用Cobertura計算代碼覆寫率

實際情況

Cobertura計算覆寫率使用Cobertura計算代碼覆寫率

根據這個demo,可以看到Cobertura統計coverage的方法不是直覺上的計算行數。實際上是對編譯後的class進行插樁。

在Defects4J資料集上,以Lang-1-f為例子,modified class為org.apache.commons.lang3.math.NumberUtils,源代碼有1436行,但是Cobertura工具統計出來的結果為373/380。

Cobertura計算覆寫率使用Cobertura計算代碼覆寫率