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

Spring Boot 2.x中Mock RestTemplate、MongoTemplate执行单元测试报空指针异常

问题根因

本地IDE执行测试时默认识别JUnit5注解启动Mockito扩展,而CICD环境执行maven测试时,因为项目同时存在JUnit4、JUnit5两套测试依赖,测试执行器默认匹配JUnit4,无法识别@ExtendWith(MockitoExtension.class)这类JUnit5注解,导致@Mock、@InjectMocks注解未生效,对应对象未初始化就被调用,触发空指针。

解决方案
  • 修复pom.xml依赖配置,放开junit-vintage-engine的排除规则,移除JUnit4兼容引擎,强制测试使用JUnit5执行:
<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>
    </exclusions>
</dependency>
  • 检查测试类所有注解的导入包路径,确保全部使用JUnit5的api包:
    • @Test导入org.junit.jupiter.api.Test
    • @ExtendWith导入org.junit.jupiter.api.extension.ExtendWith
  • 若仍存在问题,可在pom中显式指定maven-surefire插件的JUnit5执行规则,避免自动识别异常:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
    </plugins>
</build>
  • 额外检查业务代码拼写错误:MyTestService类中注入的MongoTemlate拼写错误,正确为MongoTemplate,该笔误也会导致正常注入失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:36:04