如何在JUnit 5中使用完整PostgreSQL数据库而非嵌入式数据库?
解决JUnit 5中使用PostgreSQL数据库而非嵌入式数据库的配置问题
问题原因
@DataJpaTest注解默认会自动将数据源替换为嵌入式数据库,即便你在测试配置文件中指定了PostgreSQL的连接信息,默认的@AutoConfigureTestDatabase行为是替换任何数据源,这就导致了配置冲突,触发了你遇到的错误。
解决方案
1. 正确配置@AutoConfigureTestDatabase注解
你需要显式设置replace = AutoConfigureTestDatabase.Replace.NONE,告诉Spring Boot不要替换你配置的自定义数据源:
修改测试类代码如下:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import static org.junit.jupiter.api.Assertions.assertTrue; @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) // 关键配置,禁用数据源替换 class GuideRepositoryTest { @Autowired private GuideRepository guideRepository; @Test void doesGuideContainsData() { assertTrue(guideRepository.doesGuideContainsData()); } }
注意:@SpringJUnitConfig和@ExtendWith(SpringExtension.class)可以移除,因为@DataJpaTest已经包含了测试上下文的相关配置,无需重复添加。
2. 确认PostgreSQL驱动依赖
确保项目中已引入PostgreSQL驱动依赖,以Maven为例,在pom.xml中添加:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>test</scope> <!-- 若仅测试环境使用则保留,主程序也需使用则移除该scope --> </dependency>
3. 验证测试配置与数据库状态
- 确认测试目录下的
application.properties中连接信息(地址、端口、数据库名、用户名、密码)完全正确 - 确保本地PostgreSQL服务处于运行状态,目标数据库
somedb已创建
为什么之前的尝试无效
你仅添加了@AutoConfigureTestDatabase注解但未指定replace属性,其默认值为Replace.ANY,仍会尝试替换数据源为嵌入式数据库,因此必须显式设置为Replace.NONE才能启用自定义的PostgreSQL数据源。
内容的提问来源于stack exchange,提问作者shortduck
相关产品推荐
相关产品推荐

