使用MockMvc测试Spring Reactive WebClient时调用.block()抛NoSuchFieldError错误
问题解决:WebClient调用
block()抛出NoSuchFieldError: NETWORK_INTERFACES 这个错误是Netty版本冲突导致的,Spring Boot 2.7.9自带的Netty版本与OkHttp依赖间接引入的Netty版本不兼容,引发类字段找不到的问题。
解决方案步骤
1. 排查依赖冲突
执行Maven命令查看依赖树,定位冲突的Netty包:
mvn dependency:tree
重点查找io.netty:netty-*相关依赖,确认是否有版本不一致的情况,尤其是OkHttp依赖是否引入了非Spring Boot管理的Netty版本。
2. 统一Netty版本
利用Spring Boot的依赖管理机制,强制所有Netty相关依赖使用Spring Boot指定的版本:
- 在
pom.xml中添加Netty版本锁定(Spring Boot 2.7.9对应的Netty版本为4.1.87.Final):
<dependencyManagement> <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-bom</artifactId> <version>4.1.87.Final</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
- 或者直接排除OkHttp依赖中可能引入的冲突Netty模块:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> <scope>test</scope> <exclusions> <exclusion> <groupId>io.netty</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>mockwebserver</artifactId> <version>4.9.3</version> <scope>test</scope> <exclusions> <exclusion> <groupId>io.netty</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency>
3. 优化WebClient创建方式
避免直接调用WebClient.create(),改用Spring Boot自动配置的WebClient.Builder构建实例,确保使用兼容的HttpClient配置:
@Autowired private WebClient.Builder webClientBuilder; @Test public void someTestHere() throws InterruptedException { WebClient webClient = webClientBuilder.baseUrl(mockWebServer.url("/").toString()).build(); webClient.get().uri("hello").retrieve().toBodilessEntity().block(); }
4. 验证修复
重新运行测试,确认NoSuchFieldError是否消失。如果仍有问题,再次检查依赖树,排查是否还有其他依赖引入了冲突的Netty版本。
内容的提问来源于stack exchange,提问作者Cal Reyes
相关产品推荐
相关产品推荐

