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

Spring Boot 2集成Spock测试:应用上下文无法启动问题求助

解决Spock测试中Spring上下文无法启动、@Autowired空指针的问题

我之前也踩过这个坑,结合你的Spring Boot 2.0.0 + Spock 1.1 + Groovy 2.4.14的环境配置,咱们一步步排查解决:

1. 检查测试类的核心注解与结构

首先得确保你的测试类是Spock能识别的Spring测试类,正确的结构应该是这样:

@SpringBootTest(classes = RecruitApplication.class) // 这里要填对你的Spring Boot主启动类
class YourTestSpec extends Specification {

    @Autowired
    private YourDependency yourDependency // 要注入的依赖

    def "测试依赖调用"() {
        when:
        def result = yourDependency.doSomething()

        then:
        result != null
    }
}

注意几个关键点:

  • 必须继承spock.lang.Specification,否则Spock的测试 runner不会处理这个类,自然不会启动Spring上下文
  • 如果不需要Web环境,建议显式指定webEnvironment = SpringBootTest.WebEnvironment.NONE,避免不必要的上下文加载问题
  • 确认@SpringBootTest里的classes参数指向了正确的主启动类,别写错类名

2. 验证依赖包的兼容性与冲突

你当前的依赖版本是匹配的(Groovy 2.4.14对应Spock 1.1-groovy-2.4),但可以排查下是否有依赖冲突:

  • 用Gradle的话,执行./gradlew dependencies;用Maven的话执行mvn dependency:tree
  • 检查输出中是否有其他版本的Groovy、Spring Context或Spock相关包被引入,如有冲突可以用依赖排除来解决

3. 检查包扫描范围是否覆盖Bean

如果你的测试类和主启动类不在同一个包(或子包)下,@SpringBootTest默认不会扫描到你的业务Bean,导致@Autowired找不到依赖。这时候可以:

  • 把测试类移到主启动类的子包下(推荐)
  • 或者在@SpringBootTest里添加scanBasePackages参数指定扫描范围,比如:
    @SpringBootTest(classes = RecruitApplication.class, scanBasePackages = "com.yourcompany.recruit")
    

4. 确认被注入的Bean已正确注册

如果你的依赖Bean没有被Spring识别,比如忘记加@Service/@Component/@Repository等注解,那即使上下文启动了,@Autowired也会拿不到实例。可以在测试类里加个调试代码验证:

@Autowired
private ApplicationContext context

def setup() {
    // 打印所有注册的Bean名称,检查你的依赖是否在其中
    println "已注册的Bean: ${context.beanDefinitionNames}"
}

5. 清理构建缓存重试

有时候构建缓存会导致依赖加载异常,试试这些操作:

  • 清理IDE的缓存(比如IntelliJ的File -> Invalidate Caches...)
  • 删除项目的构建目录(Gradle的build,Maven的target)
  • 重新构建项目后再运行测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:35:14