首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

JUnit「No tests found matching」異常排查:Spring 版本衝突導致測試發現失效

     編輯:Java 綜合教學

異常現場還原

執行 JUnit 測試時拋出如下堆疊信息:

java.lang.Exception: No tests found matching [
  {ExactMatcher:fDisplayName=test2],
  {ExactMatcher:fDisplayName=test2(cn.amumu.spring.test.shiro.ShiroTest12)],
  {LeadingIdentifierMatcher:fClassName=cn.amumu.spring.test.shiro.ShiroTest12,fLeadingIdentifier=test2]]
from org.junit.internal.requests.ClassRequest@33f88ab
    at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:37)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:77)
    ...

乍看之下像是測試方法命名、註解缺失或字節碼找不到,但經排查發現真兇竟是 Spring 版本不一致。

根因定位:spring-test 與核心容器版本脫節

  • 專案引入 spring-test:4.0.x
  • 其餘 Spring 模組(core, context, beans 等)仍停留在 3.4.x

JUnit 通過 SpringJUnit4ClassRunner 啟動測試上下文時,依賴 spring-test 中的 TestContextManager 與核心容器協作。版本不匹配導致 TestContextBootstrapper 無法正確識別測試類上的 @ContextConfiguration 等註解,進而拋出「No tests found matching」誤導性錯誤。

解決方案:統一版本號

<!-- pom.xml 片段 -->
<properties>
    <spring.version>4.3.25.RELEASE</spring.version> <!-- 統一升級或降級 -->
</properties>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    <scope>test</scope>
</dependency>
<!-- 其他 spring-* 同理 -->

執行 mvn dependency:tree 驗證無版本衝突後,重新運行測試即可通過。

避坑檢查清單

  1. 統一 BOM: 引入 spring-framework-bom 管理全家桶版本。
  2. 檢查傳遞依賴: 使用 mvn dependency:analyze 發現版本漂移。
  3. IDE 緩存清理: IntelliJ 執行 File → Invalidate Caches / Restart;Eclipse 執行 Project → Clean。
  4. 註解完整性: 確認測試類標註 @RunWith(SpringRunner.class) 且方法有 @Test。

延伸思考

該異常屬於「異常信息與根因嚴重不符」的典型案例。建議團隊建立 依賴版本鎖定機制(如 Enforcer Plugin 或 Gradle Platform),從源頭杜絕此類「偽裝成測試發現失敗的版本衝突」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved