Spring Boot Actuator与CORS测试失败:如何跳过数据库连接启动测试?
问题描述
我的Spring Boot应用配置了数据源,同时实现了CORS配置和HttpSecurity的.antMatchers请求授权逻辑。之前配置文件用明文数据库密码时,应用构建、测试、启动都正常。
把凭据迁移到CREDHUB服务后,本地构建通过Gradle激活测试profile(用未提交的含明文账号密码的配置文件)解决了问题,但Jenkins上的Actuator和CORS测试开始失败——因为Jenkins没配置CREDHUB访问权限。
现在的问题是:测试会启动整个应用,进而尝试连接真实数据库,但本地拿不到数据库凭据,缺少db前缀的配置导致测试启动失败。想知道怎么在不建立数据库连接的情况下完成这些测试?
相关配置文件
app.yml
spring: datasource: driver-class-name: org.abc.jdbc.Driver username: ${db.username} password: ${db.password} url: jdbc:abc://${db.host}:${db.port}/${db.schema}
ActuatorSecurityTest.java
@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = RANDOM_PORT) @Import(ExceptionHandlerConfiguration.class) @AutoConfigureWebTestClient(timeout = "30000") class ActuatorsSecurityTest { @Autowired private WebTestClient webClient; /*********************************************************************************************** * ENDPOINTS: Actuator ***********************************************************************************************/ @Test void should_allowActuatorInfoEndpoint_withoutAuthentication() { webClient.get().uri("/actuator/info").exchange().expectStatus().is2xxSuccessful(); } @Test void should_notAllowSensitiveActuatorEndpoints_withInValidAuthentication() { webClient.get().uri("/actuator/env").header("Authorization", "Basic xxx").exchange().expectStatus().is4xxClientError(); } }
解决方法
方法1:创建测试专用配置,排除数据源自动配置
在src/test/resources下新建application-test.yml,添加配置跳过数据源相关自动配置:
spring: autoconfigure: exclude: - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration - org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration - org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
然后在测试类上激活这个测试profile:
@SpringBootTest(webEnvironment = RANDOM_PORT) @ActiveProfiles("test") // 新增激活测试profile @Import(ExceptionHandlerConfiguration.class) @AutoConfigureWebTestClient(timeout = "30000") class ActuatorsSecurityTest { // 测试代码保持不变 }
方法2:在测试类直接排除数据源自动配置
不需要额外配置文件,直接在测试类注解中排除相关自动配置类:
@ExtendWith(SpringExtension.class) @SpringBootTest( webEnvironment = RANDOM_PORT, exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class } ) @Import(ExceptionHandlerConfiguration.class) @AutoConfigureWebTestClient(timeout = "30000") class ActuatorsSecurityTest { // 测试代码保持不变 }
方法3:Mock数据源Bean(应对有依赖的场景)
如果应用中有其他Bean依赖DataSource,用@MockBean模拟数据源实例,避免Spring尝试创建真实连接:
@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = RANDOM_PORT) @Import(ExceptionHandlerConfiguration.class) @AutoConfigureWebTestClient(timeout = "30000") class ActuatorsSecurityTest { @MockBean private DataSource dataSource; // 新增模拟数据源 @Autowired private WebTestClient webClient; // 测试代码保持不变 }
内容的提问来源于stack exchange,提问作者dilbert2219
相关产品推荐
相关产品推荐

