@WebFluxTest在Jenkins流水线运行抛出Binder未注册错误如何解决
问题根因
该错误本质是切片测试@WebFluxTest加载上下文时,触发了Spring Cloud GCP的自动配置,但切片测试默认不会加载属性绑定所需的Binder实例,同时因为Jenkins环境存在GCP相关的环境变量/系统参数,触发了GCP自动配置的激活条件,本地没有对应参数所以不会触发,才会出现环境差异问题。
排查与解决方案
- 第一步:确认Jenkins环境差异
检查Jenkins测试任务的启动参数、系统环境变量,是否存在spring.cloud.gcp.*开头的配置项,本地测试时加上相同的配置即可复现问题。 - 第二步:测试类排除GCP自动配置
@WebFluxTest是切片测试,仅需要加载Controller相关的Bean,无需加载GCP配置,直接在注解中排除GCP的自动配置类即可:@WebFluxTest(controllers = Controller.class, excludeAutoConfiguration = { com.google.cloud.spring.autoconfigure.core.GcpContextAutoConfiguration.class, com.google.cloud.spring.autoconfigure.core.GcpCredentialsAutoConfiguration.class }) public class ControllerTest { // 原有测试逻辑不变 } - 第三步:校验依赖版本一致性
执行mvn dependency:tree检查spring-boot-context-properties依赖版本是否和Spring Boot 2.5.5匹配,若Jenkins的依赖拉取策略为每次拉取最新,可能出现依赖版本冲突,可在pom中强制指定该依赖版本为2.5.5:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>2.5.5</version> <scope>test</scope> </dependency> - 临时兜底方案
如果上述方案仍不生效,可在测试类中手动注册Binder实例:@WebFluxTest(controllers = Controller.class) @Import(ControllerTest.TestConfig.class) public class ControllerTest { @TestConfiguration static class TestConfig { @Bean public org.springframework.boot.context.properties.bind.Binder binder(org.springframework.core.env.ConfigurableEnvironment environment) { return org.springframework.boot.context.properties.bind.Binder.get(environment); } } // 原有测试逻辑不变 }
内容的提问来源于stack exchange,提问作者Vivek T S
相关产品推荐
相关产品推荐

