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

Spring Boot 2.3.2集成Spock测试ApplicationContext为null问题求解

问题根因

你当前的配置存在3个核心错误,导致Spring上下文没有被Spock测试加载、@Autowired注入失效:

  • 缺少Spock与Spring整合的核心依赖spock-spring,仅引入spock-core无法识别Spring相关注解
  • 错误引入了Maven专属的gmavenplus-plugin依赖,Gradle环境无需该依赖
  • Spock版本与SpringBoot 2.3.2的适配性存在问题,同时重复声明了spock-core依赖

修复步骤

1. 调整Gradle配置

首先在build.gradle的plugins块中引入Groovy插件,否则无法编译Groovy测试代码:

plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
    id 'groovy' // 新增groovy插件
}

然后删除你原有错误的Spock相关依赖,替换为以下配置:

dependencies {
    // 原有业务依赖保留即可
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'junit', module: 'junit'
    }
    // Spock核心与Spring整合依赖,版本与SpringBoot 2.3.x默认Groovy版本匹配
    testImplementation 'org.spockframework:spock-core:1.3-groovy-2.5'
    testImplementation 'org.spockframework:spock-spring:1.3-groovy-2.5'
    // JUnit平台引擎,用于运行Spock测试
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

2. 验证测试类配置

确认你的测试类存放路径为src/test/groovy下的对应包目录,你现有的测试类代码本身符合要求,无需额外修改:

@SpringBootTest(classes = PrototypeApplication.class)
class PrototypeApplicationSpec extends Specification {

    @Autowired
    ApplicationContext context

    def "test context loads"() {
        expect:
        context != null
    }
}

3. 异常排查

如果调整配置后仍然存在注入失败问题,可执行以下操作排查:

  • 检查启动类PrototypeApplication的包扫描范围是否包含测试类所在的包
  • 执行./gradlew clean build --refresh-dependencies清除Gradle缓存后重新运行测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:36:08