测试进行代码单元测试时,都应该执着于实现100%的覆盖率。代码覆盖率越高,并不能说明质量就越好,但是代码覆盖率很低,那么质量的风险肯定高。
I’m not a great programmer; I’m just a good programmer with great habits. --Kent Beck
今天简单介绍下Java的一款开源的覆盖率工具JaCoCo。
官网:https://www.jacoco.org/jacoco/
直接代码中进行配置:https://github.com/supremecsp/geektime-todo
例子由极客时间《程序员的测试课》课程源码进行调整
个人习惯用maven开发,调试工具idea;
官网配置:https://www.jacoco.org/jacoco/trunk/doc/maven.html
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.4</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<!-- attached to Maven test phase -->
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
配置完成先clean再点test

编译完成在target找到index.html文件

浏览器打开即可看到覆盖率信息

Jacoco从多种角度对代码进行了分析,包括指令(Instructions,C0 Coverage),分支(Branches,C1 Coverage),圈复杂度(Cyclomatic Complexity),行(Lines),方法(Methods),类(Classes)。
点进去类可能会有三种颜色
红色:无覆盖,没有分支被执行。
黄色:部分覆盖,部分分支被执行。
绿色:全覆盖,所有分支被执行。
具体字段代表可看:https://www.jianshu.com/p/4c728b39185e
代码有时还是会出现无法通过测试的第三方代码/异常,如图所示:你无法模拟出IO异常;
此时由于其它程序库造成难以测试的问题,我们可以做一层层薄薄的封装,然后,在覆盖率检查中忽略它。封装和忽略,缺一不可。
![]()
忽略的话pom的plugin中做下配置即可(其他的操作参数自行浏览官网)
<configuration>
<excludes>
<exclude>com/github/dreamhead/todo/util/**/*</exclude>
<exclude>**/*Bootstrap.*</exclude>
</excludes>
</configuration>

只想查看某个测试类覆盖率的话,idea可在Run/Debug Configurations中配置Code Coverage为JaCoCo,Run XXX with Coverage启动,结构down出来即可看到覆盖率
![]()
![]()
![]()
网友评论