jenkins使用jacoco插件检测代码覆盖率(八)

时间:2023-03-09 04:07:41
jenkins使用jacoco插件检测代码覆盖率(八)

代码覆盖率:类覆盖,方法覆盖,行覆盖,指令覆盖……(简而言之,就是判断有没有被执行)

覆盖率 = 已经执行的代码 / 总代码

(1)创建maven项目,配置pom.xml如下

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cn.demo</groupId>
<artifactId>answers</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>answers</name>
<url>http://maven.apache.org</url> <build>
<finalName>answers</finalName>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${compiler.source}</source>
<target>${compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin> <!--检测代码覆盖率的插件-->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</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> </plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler.source>1.7</compiler.source>
<compiler.target>1.7</compiler.target>
<junit.version>4.12</junit.version>
</properties> <dependencies>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

(2)下载jacoco-plugin插件

在jenkins的可选插件中,选中  jacoco-plugin 插件 直接下载

(3)jenkins使用jacoco-plugin插件构建项目的配置

在构建后操作中 --》 选中  Record JaCoCo coverage report  开始详细配置

Path to exec files:target/jacoco.exec    #这里指定你的jacoco.exec文件的位置,文件名必须是 jacoco.exec ,,否则会出错 ,这里最好配置为如图所示

Path to class directories: target/classes      #这里配置源代码的字节码文件目录位置

Path to source directories :src/main/java      #这里配置为源码的目录位置

Inclusion : 标明还需要检测的文件

Exclusions:标明需要除外的文件(不想被检测的文件)

下面的值都是属于 1-100 (代表代码覆盖率)

口 Change build status according the thresholds  #选中这里可以改变项目的构建状态

(乌云数必须小于太阳数 ,所有的值必须小于100 ,大于的话系统会自动设置为100)

当项目的真实代码覆盖率 小于太阳所标明的值时,项目会构建不稳定 黄色 unstable

这里 %Method 对应太阳这一列的值 设置为 100:表示每个方法都要被执行,整个项目才能稳定构建;只要有一个方法没有被执行,整个项目就会构建不稳定。

注释:项目的真实代码覆盖率 jenkins会计算出来的

比如: 当你的method那一列 太阳对应的值为 100 ,而你的项目中 总共有10个方法,其中有8个被执行了,还有2个没有被执行,那么你的真实代码覆盖率为 80,这时候整个项目构建结果为 unstable (黄色标识)

口 fail the build if the coverage degrades more than the delta thresholds   #这是和上一次构建的代码覆盖率做对比的

选中后,并且全部值设置为0 。如果本次构建的覆盖率低于上次的覆盖率,整个项目就会构建失败

这些值都可以改变,但是设置为0 时,表示覆盖率只能越来越高,不能低。 反正就会有容错率。

jenkins使用jacoco插件检测代码覆盖率(八)

到这里,可以正常构建了。