升级Spring Framework到6.0.1后Controller测试MockMvc为空问题
解决Spring Boot 3+Spock测试中MockMvc注入为null的问题
1. 适配Spock依赖版本
Spring Boot 3.x(配套Spring 6)要求Spock版本至少为2.3,且需适配Groovy 4.0和Java 17。调整你的构建依赖:
Gradle示例
testImplementation 'org.spockframework:spock-spring:2.3-groovy-4.0' testImplementation 'org.springframework.boot:spring-boot-starter-test' // 排除JUnit 4,避免与JUnit 5冲突 testImplementation('org.spockframework:spock-core:2.3-groovy-4.0') { exclude group: 'junit', module: 'junit' }
Maven示例
<dependency> <groupId>org.spockframework</groupId> <artifactId>spock-spring</artifactId> <version>2.3-groovy-4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency>
2. 简化测试类注解
@WebMvcTest注解已经自动包含@AutoConfigureMockMvc,无需重复添加,避免上下文初始化冲突:
@WebMvcTest(NominationController.class) class NominationIsolationTest extends Specification { @Autowired MockMvc mockMvc def "should return status created with response when post nominations given valid nomination"() { given: def body = // 你的请求体JSON内容 when: def response = mockMvc.perform(post("/nominations") .content(body) .contentType(MediaType.APPLICATION_JSON)) then: response.andExpect(status().isCreated()) // 其他业务断言逻辑 } }
3. 排查安全配置影响
重构安全配置后,可能导致测试上下文加载异常。可以尝试排除安全自动配置,验证是否是安全配置导致的问题:
@WebMvcTest( value = NominationController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class ) class NominationIsolationTest extends Specification { // ... }
如果自定义了安全配置类,也可以直接排除该类:
@WebMvcTest( value = NominationController.class, excludeFilters = @ComponentScan.Filter( type = FilterType.ASSIGNABLE_TYPE, classes = CustomSecurityConfig.class ) )
4. 确认包路径与组件扫描
确保测试类的包路径和主应用启动类的包路径一致,或者主应用类的@ComponentScan覆盖到NominationController所在的包,否则@WebMvcTest无法识别Controller,导致上下文初始化不完整。
5. 修正代码语法错误
你提供的测试代码中when块存在明显语法错误(mockMvc")),需修正为标准的mockMvc.perform()调用,语法错误可能间接导致测试上下文加载异常。
内容的提问来源于stack exchange,提问作者Yingjie Guan
相关产品推荐
相关产品推荐

