Spring Boot中JUnit测试时H2数据库无法查看生成表的解决方法
解决JUnit测试H2内存库看不到生成表的问题
问题背景
使用H2内存数据库进行JUnit测试(不启动完整应用),运行Controller/Service/Repository测试方法后,无法在IntelliJ的数据源中看到生成的表。已尝试添加@Rollback(value = false)和@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)注解,但问题未解决。
当前配置文件application.integration.properties内容:
spring.h2.console.enabled=true spring.datasource.name=test spring.datasource.username=sa spring.datasource.password= spring.datasource.driver-class-name=org.h2.Driver spring.sql.init.mode=always spring.datasource.url=jdbc:h2:mem:weatherdb?mode=MySQL spring.sql.init.platform=h2 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update
IntelliJ配置H2数据源时,URL为jdbc:h2:mem:weatherdb?mode=MySQL,用户名sa,无密码。
解决方案
1. 修正H2内存库的生命周期配置
H2内存数据库默认会在最后一个连接关闭时销毁,而JUnit测试结束后测试上下文关闭,数据库随之消失。需修改数据源URL,添加参数让数据库保持存活:
spring.datasource.url=jdbc:h2:mem:weatherdb?mode=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
DB_CLOSE_DELAY=-1:禁止数据库在连接关闭时自动销毁DB_CLOSE_ON_EXIT=FALSE:禁止JVM退出时关闭数据库
2. 确保测试类正确加载配置并禁用数据源替换
- 确认测试类加载了
application.integration.properties,比如添加注解:
或者通过激活profile加载:@TestPropertySource(locations = "classpath:application.integration.properties")@SpringBootTest(profiles = "integration") - 确保
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)注解被正确应用在测试类或基类上,避免Spring Boot自动替换为默认测试数据源。
3. 在测试运行期间查看H2数据库
内存数据库仅在测试上下文运行时存在,测试结束后会销毁。需在测试执行过程中查看:
- 在测试方法中添加断点,暂停测试执行
- 打开H2控制台(若测试上下文启动web环境,可访问
http://localhost:8080/h2-console),或通过IntelliJ的数据源连接,确保连接URL与配置文件完全一致(包含所有参数)
4. 验证DDL语句是否执行
开启SQL日志,确认Hibernate是否生成并执行了建表语句:
在配置文件中添加:
logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
运行测试后查看日志,检查是否有CREATE TABLE相关的SQL语句,确认DDL是否正常执行。
5. 检查事务与回滚配置
- 确保
@Rollback(false)注解生效:如果测试类使用了@Transactional(Spring Boot测试默认添加),@Rollback(false)会让事务提交,避免数据被回滚。 - 如果使用
@DataJpaTest这类切片测试注解,必须搭配@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE),否则框架会强制替换为嵌入式测试数据源。
内容的提问来源于stack exchange,提问作者Sercan Noyan Germiyanoğlu
相关产品推荐
相关产品推荐

