問題現象
Spring Boot 項目,在編寫單元測試時,使用了 JUnit 4.13.2 以上的版本。
爲了讓 Maven 能自動運行單元測試,需要引入 Maven Surefire 或 Maven Failsafe 插件。
項目中使用的 maven-surefire-plugin 版本號爲 2.22.2,在通過 mvn clean package
打包編譯時,沒有執行單元測試。
在經過一系列的測試後,發現只有 2.21 及以下版本的 maven-surefire-plugin 可以正常運行單元測試。
解決方法
根據上面的分析,最直觀的解決方法就是降低 maven-surefire-plugin 的版本號。
但作爲一個程序開發人員,怎麼能止步於此呢?
去看看 maven-surefire-plugin 插件的作用原理,它默認是按照如下邏輯去尋找 JUnit 並執行測試用例的:
if the JUnit version in the project >= 4.7 and the parallel attribute has ANY value
use junit47 provider
if JUnit >= 4.0 is present
use junit4 provider
else
use junit3.8.1
如果不使用默認方式去查找 JUnit 的包,我們可以通過手動置頂內置的依賴,比如:
1、如果是 JUnit4.7 及以上版本,可以明確聲明:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
</plugin>
2、JUnit 4.0 (含) 到 JUnit4 .7 (不含) 的版本,這樣聲明:
3、JUnit 3.8 (含) 到 JUnit 4.0 (不含) 的版本,這樣聲明:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit3</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
</plugin>
4、JUnit 3.8 以下的版本,啊哦,surefire 已經不支持這麼低版本的 JUnit 了,趕緊升級下 JUnit 的版本吧。
參考資料:
版權聲明
出處:博客園-瘦風的南牆(https://www.cnblogs.com/shoufeng)
感謝閱讀,公衆號 「瘦風的南牆」 ,手機端閱讀更佳,還有其他福利和心得輸出,歡迎掃碼關注🤝
本文版權歸博主所有,歡迎轉載,但 [必須在頁面明顯位置標明原文鏈接],否則博主保留追究相關人士法律責任的權利。