You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.4升级至2.7.8后测试报Mockito类初始化错误

解决方案

核心问题分析

测试失败的根源是依赖版本不兼容:

  • Spring Boot 2.7.8默认引入Mockito 4.x,但你使用的PowerMock 2.0.0仅支持Mockito 2.x,版本不匹配导致Mockito初始化失败。
  • 手动指定的spring-security-test:5.4.5与Spring Boot 2.7.8配套的Spring Security 5.7.x版本冲突,加剧依赖混乱。
  • 冗余的junit:junit依赖可能引发重复依赖冲突。

具体修改步骤

1. 升级PowerMock到兼容Mockito 4.x的版本

PowerMock 2.0.0不支持Mockito 4+,直接升级到2.10.0及以上版本(该版本开始支持Mockito 4.x),同时替换对应的Mockito API依赖:

<!-- 替换旧的PowerMock依赖 -->
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.10.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito4</artifactId>
    <version>2.10.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-core</artifactId>
    <version>2.10.0</version>
    <scope>test</scope>
</dependency>

2. 移除手动指定的Spring Security Test版本

Spring Boot父依赖已经统一管理了spring-security-test的版本,删除手动指定的version标签,避免版本冲突:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
    <!-- 移除version标签,由父依赖自动匹配兼容版本 -->
</dependency>

3. 清理冗余依赖

删除单独声明的junit:junit依赖,因为spring-boot-starter-test和powermock-module-junit4已经包含了JUnit 4的必要依赖,重复声明可能引发冲突。

4. 确保Mockito版本一致(可选)

如果升级后仍有冲突,可以在spring-boot-starter-test中排除自带的Mockito依赖,强制使用PowerMock配套的版本:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
        </exclusion>
        <!-- 排除自带的Mockito依赖 -->
        <exclusion>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
        </exclusion>
    </exclusions>
</dependency>

验证修改

执行mvn dependency:tree命令,检查输出中所有Mockito相关依赖的版本是否统一,且与PowerMock版本兼容。之后重新运行测试即可。

内容的提问来源于stack exchange,提问作者Magda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:54:56