Spring Boot 3.1.0测试中H2配置未从application-test.properties生效
解决Spring Boot 3.1.0 @DataJpaTest不加载H2配置的问题
以下是针对你遇到问题的具体排查和解决步骤:
1. 修正@DataJpaTest的自动数据库配置
@DataJpaTest默认会自动替换所有数据源为嵌入式内存库(不管你配置了什么),这是核心问题。你需要显式禁用这个行为,让Spring使用你指定的H2配置:
@DataJpaTest @ActiveProfiles("test") // 关键:禁止自动替换数据源 @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) class UserJpaRepositoryTest { // 你的测试代码 }
2. 检查application-test.properties的配置键是否正确
确保H2的配置使用Spring Boot标准前缀,不要用错误的键名。正确的配置示例:
# src/test/resources/application-test.properties spring.datasource.url=jdbc:h2:mem:custom-test-db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= # 可选:指定Hibernate方言 spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # 可选:开启SQL日志便于排查 spring.jpa.show-sql=true
注意:不要用spring.h2.*开头的键配置数据源,那是H2控制台的专属配置。
3. 确认依赖配置正确
确保你的pom.xml(或build.gradle)中正确引入了H2和测试依赖,且版本与Spring Boot 3.1.0匹配:
Maven示例:
<dependencies> <!-- 测试核心依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- H2数据库依赖(仅测试环境使用) --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> </dependencies>
Gradle示例:
dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'com.h2database:h2' }
4. 清理构建缓存并重新运行测试
有时候旧的构建缓存会导致配置不生效,执行以下命令清理后再测试:
- Maven:
mvn clean test - Gradle:
./gradlew cleanTest test
5. 验证配置是否加载(可选)
开启Debug日志查看Spring Boot是否正确加载了test配置:
在application-test.properties中添加:
logging.level.org.springframework=DEBUG
运行测试后,查看控制台输出,确认是否有类似以下日志:
Loaded environment profile 'test'
Loaded property source 'class path resource [application-test.properties]'
如果看不到这些日志,说明配置文件根本没被加载,需要检查文件路径、命名是否完全正确(注意大小写,比如Application-Test.properties是错误的)。
内容的提问来源于stack exchange,提问作者Ali Behzadian Nejad
相关产品推荐
相关产品推荐

