集成测试无法使用H2测试库,报MySQL通信链接失败问题
集成测试使用H2内存数据库时出现MySQL连接失败的解决方法
问题场景
尝试用H2内存数据库做集成测试(测试后自动销毁),但运行测试时抛出错误:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
相关代码及配置如下:
业务测试代码
@SpringBootTest() public class PostePomponServiceIT{ @Autowired private PostePomponService postePomponService; @Autowired private PostePomponRepository postePomponRepository; @Test public void addPostePompon_Ok() throws BadRequestException { PostePomponForm postePomponForm = new PostePomponForm(); postePomponService.add(postePomponForm); assertEquals(1, postePomponRepository.findAll().size()); } }
主测试类
package com.MailleCoTech.SuiviProduction; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.PropertySource; @SpringBootTest(classes = SuiviProductionApplication.class) @PropertySource("application-test.properties") class SuiviProductionApplicationTests { @Test void contextLoads() { } }
application-test.properties配置
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
问题原因
测试时系统仍在尝试连接MySQL,说明application-test.properties的配置未被正确加载,或是被主环境的MySQL配置覆盖了。
解决方案
1. 改用@ActiveProfiles指定测试环境
Spring Boot中推荐用@ActiveProfiles("test")来加载测试环境配置,替换原有的@PropertySource:
更新主测试类
package com.MailleCoTech.SuiviProduction; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @SpringBootTest(classes = SuiviProductionApplication.class) @ActiveProfiles("test") class SuiviProductionApplicationTests { @Test void contextLoads() { } }
更新业务测试类
@SpringBootTest @ActiveProfiles("test") public class PostePomponServiceIT{ // 原有代码保持不变 }
2. 确认配置文件位置
确保application-test.properties放在src/test/resources目录下,符合Spring Boot环境配置文件的加载规范。
3. 检查H2依赖是否存在
确保构建文件中添加了H2的测试依赖:
Maven(pom.xml)
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
Gradle(build.gradle)
testImplementation 'com.h2database:h2'
4. 清除缓存并重新运行
- 执行构建工具的清理命令(Maven:
mvn clean;Gradle:gradle clean) - 重启IDE后重新运行测试
验证
修改后运行测试,系统将加载H2内存数据库配置,不再尝试连接MySQL,测试完成后H2内存数据库会自动销毁。
内容的提问来源于stack exchange,提问作者user13906062
相关产品推荐
相关产品推荐

