JaCoCo 代碼覆蓋率工具(基於Maven+TestNG)


JaCoco是一個代碼覆蓋率庫。

官方網站:http://www.jacoco.org/

 

安裝:

 以 Maven(http://www.testclass.net/maven/) 安裝為例:

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.7.9</version>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
                <execution>
                    <id>report</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

 

使用:

Maven項目目錄如下:

創建被測試類 Count.java

public class Count {

    /**
     * 計算並返回兩個參數的和
     */
    public int add(int x ,int y){
        return x + y;
    }

    /**
     * 計算並返回兩個參數的和
     */
    public int sub(int x ,int y){
        return x - y;
    }

}

代碼很簡單,這里不做過多解釋。

接下來創建測試類CountTest.java。

import org.testng.annotations.Test;

import static org.testng.AssertJUnit.assertEquals;


public class CountTest {

    @Test
    public void testAdd() {
        Count count = new Count();
        int result = count.add(2,2);
        assertEquals(result, 4);
    }

}

通過TestNG單元測試框架來運行測試用例,注意這里只編寫了針對Count類的 add()方法進行測試。

 

運行:

切換到jacocoTest項目根目錄下,執行“mvn install”命令。

 

查看:

切換到項目下的“\target\site\jacoco\”目錄,打開index.html文件。

 

通過JaCoCo工具分析可以清楚地看哪些代碼被執行了,而哪些未被執行。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM