代码覆盖率
What is Code Coverage - from Wikipedia
In computer science, test coverage is a measure used to describe the degree to which the source code of a program is executed when a particular test suite runs. A program with high test coverage, measured as a percentage, has had more of its source code executed during testing, which suggests it has a lower chance of containing undetected software bugs compared to a program with low test coverage.
当然,代码覆盖率越高并不代表代码本身质量越高,因为程序员总有办法写出单元测试方法来提升自己项目的代码覆盖率。所以代码覆盖率只是一个用来找出未检测代码的工具,以此来降低可能这些未检测区域给整体项目带来的风险。可以参考Martin Fowler对代码覆盖率的理解:Test Coverage - Martin Fowler
JaCoCo
Code coverage is a software metric used to measure how many lines of our code are executed during automated tests.
In this article we’re going to stroll through some practical aspects of using JaCoCo – a code coverage reports generator for Java projects.
Maven + JaCoCo
参考:Maven – JaCoCo code coverage example
在mvn repository 搜索最新的 jacoco-maven-plugin,在pom文件中添加:
<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>
注意,这组plugin标签应添加至project - build - plugins中,而不是添加至pluginManagement中。否则最终code coverage可能显示为0%
Java Main Source
package com.jake.jacoco.builder;
import org.apache.commons.lang3.StringUtils;
class MessageBuilder {
static final String PROVIDED = "Please provide a name!";
static final String HELLO = "Hello ";
String getMessage(String name) {
StringBuilder result = new StringBuilder();
if (StringUtils.isBlank(name)) {
result.append(PROVIDED);
} else {
result.append(HELLO).append(name);
}
return result.toString();
}
}
JUnit Test Source
package com.jake.jacoco.builder;
import org.junit.Test;
import static org.junit.Assert.*;
public class MessageBuilderTests {
@Test
public void testNameMessage() {
String name = "Jake";
MessageBuilder messageBuilder = new MessageBuilder();
assertEquals(MessageBuilder.HELLO + name, messageBuilder.getMessage(name));
}
@Test
public void testEmptyMessage() {
MessageBuilder messageBuilder = new MessageBuilder();
assertEquals(MessageBuilder.PROVIDED, messageBuilder.getMessage(" "));
}
@Test
public void testNullMessage() {
MessageBuilder messageBuilder = new MessageBuilder();
assertEquals(MessageBuilder.PROVIDED, messageBuilder.getMessage(null));
}
}
Maven Test
IntelliJ IDEA -> View -> Terminal -> 执行 mvn clean test
或
IntelliJ IDEA -> View -> Maven -> Lifecycle -> click ‘test’
执行完毕后,targer -> site -> index.html,可以看到Jacoco检测出的代码覆盖率:
点击进去后可以看到方法的详细代码覆盖情况:
展示在SonarQube中
如果您的代码仓库集成了SonarQube,那么SonarQube的检测结果图中的Coverage一栏显示的即为JaCoCo的检测结果。