Spring Boot+JUnit5+Testcontainers集成测试启动失败求助
Spring Boot集成JUnit 5+Testcontainers时数据库连接Bean创建异常
依赖配置(pom.xml)
使用Testcontainers 1.19.3版本,相关依赖如下:
<properties> <testcontainers.version>1.19.3</testcontainers.version> </properties> <dependencies> <dependency> <groupId>org.testcontainers</groupId> <artifactId>junit-jupiter</artifactId> <version>${testcontainers.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>postgresql</artifactId> <version>${testcontainers.version}</version> <scope>test</scope> </dependency> </dependencies>
application.yml配置
spring: datasource: type: com.zaxxer.hikari.HikariDataSource url: jdbc:tc:postgresql:10.4://localhost:5432/test-tc driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver username: postgres password: postgres
测试类代码
package com.worldline.ancv.messagebroker.web.rest; import com.worldline.ancv.messagebroker.MessageBrokerApp; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest(classes = MessageBrokerApp.class) public class TestOff { @Test public void getAllLogs() { // Test implementation } }
报错信息
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'batchDataSourceInitializer' defined in class path resource [org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration$DataSourceInitializerConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.batch.BatchDataSourceScriptDatabaseInitializer]: Factory method 'batchDataSourceInitializer' threw exception; nested exception is java.lang.IllegalStateException: Failed to determine DatabaseDriver ... Caused by: java.sql.SQLException: HikariDataSource HikariDataSource (HikariPool-9) has been closed.
解决方案
- 修正JDBC URL格式:Testcontainers的JDBC URL无需指定
localhost和端口,正确格式为jdbc:tc:postgresql:10.4:///test-tc。Testcontainers会自动管理容器端口映射,手动指定端口会导致连接失败。 - 移除
driver-class-name配置:Testcontainers的JDBC URL会自动触发对应驱动,Spring Boot可自动识别,无需显式配置org.testcontainers.jdbc.ContainerDatabaseDriver。 - 版本兼容检查:若使用较新版本的Spring Boot,建议升级Testcontainers到匹配版本(如2.x系列),避免版本不兼容引发的初始化问题。
- 按需禁用Batch自动配置:若应用无需Spring Batch,可在测试类添加
@SpringBootTest(classes = MessageBrokerApp.class, exclude = BatchAutoConfiguration.class),避免Batch初始化时的数据库驱动识别异常。
内容的提问来源于stack exchange,提问作者Yaacoub EL Karari
相关产品推荐
相关产品推荐

