代码改变世界

JaCoCo 代码覆盖率工具(基于Maven+TestNG)

2017-11-29 23:22  虫师  阅读(7225)  评论(1编辑  收藏  举报

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工具分析可以清楚地看哪些代码被执行了,而哪些未被执行。

 

Web Page Counters
Computer Desks