執行 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:4.0.x3.4.xJUnit 通過 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 驗證無版本衝突後,重新運行測試即可通過。
spring-framework-bom 管理全家桶版本。mvn dependency:analyze 發現版本漂移。File → Invalidate Caches / Restart;Eclipse 執行 Project → Clean。@RunWith(SpringRunner.class) 且方法有 @Test。該異常屬於「異常信息與根因嚴重不符」的典型案例。建議團隊建立 依賴版本鎖定機制(如 Enforcer Plugin 或 Gradle Platform),從源頭杜絕此類「偽裝成測試發現失敗的版本衝突」。