Spock测试中@Autowired注入的测试对象出现空指针异常
Spock测试中@SpringBootTest未启动上下文导致注入失败
问题描述
标注@SpringBootTest的Spock测试类,尝试通过@Autowired注入BeerController时对象为空,且Spring上下文未启动。测试代码如下:
@SpringBootTest class BeerControllerTest extends Specification { @Autowired BeerController testSubject def "get beer by ID"() { when: def result = testSubject.getBeerById(UUID.randomUUID()) then: result println result } }
已引入spock-core和spock-spring依赖,仍出现该问题。
排查与解决要点
- 检查包路径匹配:Spring Boot默认扫描
@SpringBootApplication主类所在包及其子包,确保测试类和主应用类处于同包或子包下,否则Spring无法扫描到BeerController,也无法正常启动上下文。 - 确保依赖版本兼容:
spock-spring版本需与Spring Boot版本匹配,比如Spring Boot 6.x需搭配Spock 2.4+版本。示例依赖配置:dependencies { testImplementation 'org.spockframework:spock-core:2.4-M1-groovy-4.0' testImplementation 'org.spockframework:spock-spring:2.4-M1-groovy-4.0' testImplementation 'org.springframework.boot:spring-boot-starter-test' } - 显式指定主应用类:若主应用类的扫描范围特殊,可在
@SpringBootTest中指定classes属性,强制加载主应用上下文:@SpringBootTest(classes = [YourSpringBootMainClass.class]) class BeerControllerTest extends Specification { // ... } - 确认测试运行方式:在IDE中执行测试时,选择"Run as Spring Boot Test"而非普通的Spock测试运行器,避免运行器未触发Spring上下文加载。
内容的提问来源于stack exchange,提问作者spartanhooah
相关产品推荐
相关产品推荐

