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

Spock+Spring集成测试中@Autowired注入失败求助

解决Spock+Spring集成测试中@Autowired对象为null的NPE问题

我之前也踩过一模一样的坑!这个空指针异常的核心原因是你的Spock测试类没有被Spring容器正确接管,导致@Autowired注解完全没生效,underTest自然就是null了。下面给你一步步排查和解决的方案:

1. 启用Spock的Spring集成扩展

Spock和Spring集成需要专门的扩展支持,如果你用的是Spock 2.x及以上版本,必须在测试类上添加@SpringTest注解,告诉Spock启用Spring相关的扩展能力:

@ContextConfiguration(locations=["classpath:test1.xml","classpath:test2.xml"])
@SpringTest // 关键:开启Spock的Spring集成支持
class SimpleSpockIntegrationTest extends Specification {
    @Autowired SomeRepo underTest;

    @Transactional
    def "repo test" () {
        expect: // 注意:你之前写的是expected,Spock的正确断言块标签是expect
        underTest.someMethod(1) == 1;
    }
}

如果是Spring Boot项目,更推荐用@SpringBootTest替代@ContextConfiguration,它会自动加载Spring上下文,配置更简洁省心:

@SpringBootTest
class SimpleSpockIntegrationTest extends Specification {
    @Autowired SomeRepo underTest;

    @Transactional
    def "repo test" () {
        expect:
        underTest.someMethod(1) == 1;
    }
}

2. 检查Spring配置文件的有效性

确认你的test1.xml和test2.xml确实在类路径下(比如放在src/test/resources目录中),并且里面正确定义了SomeRepo的Bean:

  • 要么显式声明Bean:<bean id="someRepo" class="com.your.package.SomeRepo"/>
  • 要么通过组件扫描自动发现:<context:component-scan base-package="com.your.package"/>(前提是SomeRepo类上标注了@Repository或@Component注解)

3. 修正Spock语法错误

你代码里写的expected:是拼写错误,Spock的断言块正确标签是expect:,虽然这不是空指针的直接原因,但会导致你的断言逻辑无法正常执行,修正后才能验证结果是否符合预期。

4. 确认依赖版本兼容

确保spock-core和spock-spring的版本完全一致,并且和你使用的Spring版本匹配:

  • Spock 2.x 适配 Spring 5.x 及以上版本
  • Spock 1.x 适配 Spring 4.x 系列

按照上面的步骤调整后,underTest应该就能被Spring正常注入,空指针问题也会随之解决!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:58:13