點擊上方「AirPython」,選擇「加爲星標」html
第一時間關注 Python 技術乾貨!java
1. 前言
前面有一篇 文章 使用 Python + Coverage 來統計測試用例的代碼覆蓋率web
Jacoco 針對 Java 語言的一款開源的覆蓋率工具,能夠嵌入到 Maven、Gradle 中,提供多種尺度的覆蓋率計數器,好比:類覆蓋、行覆蓋、分支覆蓋等api
本篇將聊聊服務端代碼的覆蓋率統計,以 Spring Boot 項目爲例,使用 Jacoco + junit 來統計服務端的代碼覆蓋率瀏覽器
2. 準備
首先使用 IDEA 建立一個 Spring Boot 項目( Maven ),以以前 構建 RESTFul API 的項目 代碼爲基礎微信
而後,配置 pom.xml 文件,爲當前項目新增 jacoco 依賴 JAR 包app
<!--pom.xml-->
<!--jacoco依賴-->
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
</dependency>
jacoco 版本能夠參考:maven
https://www.eclemma.org/jacoco/index.html
接着,配置 Jacoco 插件及相關的 goal,使用 includes 和 excludes 兩個關鍵字設定包含或排除的類路徑工具
好比:這裏只統計 com.xingag.api.service 下面的類性能
<!--pom.xml-->
<!--配置Jacoco插件信息--><plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
<configuration>
<includes>
<!--只包含com/xingag/api/service/下面的類-->
com/xingag/api/service/*
</includes>
</configuration>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
最後,點擊右上角的 Maven 同步,下載依賴並配置項目
3. 實戰一下
//ScoreServiceImpl.java
package com.xingag.api.service;
//被測代碼
public class ScoreServiceImpl {
public String getScoreLevel(int score) {
String result;
if (score > 90) {
result = "優秀";
} else if (score < 90 && score >= 75) {
result = "良好";
} else if (score >= 60) {
result = "合格";
} else if (score > 40) {
result = "不合格";
} else if (score >= 0) {
result = "差";
} else {
result = "成績格式不正確";
}
return result;
}
}
//ScoreTests
//測試類
@RunWith(SpringRunner.class)
@SpringBootTest
public class ScoreTests {
...
}
//ScoreTests.java
//定義測試方法
//成績優秀
@Test
public void testLevelA() {
Assert.assertEquals(RESULT_LEVEL[0], scoreService.getScoreLevel(95));
}
//成績良好
@Test
public void testLevelB() {
Assert.assertEquals(RESULT_LEVEL[1], scoreService.getScoreLevel(80));
}
//成績及格
@Test
public void testLevelC() {
Assert.assertEquals(RESULT_LEVEL[2], scoreService.getScoreLevel(70));
}
用瀏覽器打開統計報告文件夾中的 index.html 文件,能夠很直觀的查看單元測試覆蓋率及對應測試類的具體覆蓋範圍
4. 最後
上面只是經過一個簡單的例子展現了 Jacoco 統計單元測試代碼覆蓋率的過程
實際項目中,代碼覆蓋率只能爲單元測試提供一個參考,考慮到開發效率,不能一味地追求高覆蓋率;事實上,高覆蓋率不必定能保證沒有缺陷
我已經將文中所有源碼上傳到後臺,關注公衆號後回覆「 jacoco 」便可得到所有源碼
若是你以爲文章還不錯,請你們 點贊、分享、留言下,由於這將是我持續輸出更多優質文章的最強動力!
![](http://static.javashuo.com/static/loading.gif)
本文分享自微信公衆號 - AirPython(AirPython)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。