Hic*_*TTA 5 java postgresql spring h2 spring-boot
我正在使用 Spring Boot 开发一个微服务应用程序。我的应用程序将使用 Postgres DB 进行生产配置,并使用 H2 DB 进行 Spring Boot 自动测试。因此,我的 pom.xml 包含两个依赖项(H2 + Postgres)。我尝试将 H2 依赖项与 tes 范围关联起来,将 Postgres 与运行时关联起来,如下所示:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我可以看到,在运行mvn test时,Spring Boot 默认选择 postgres 数据库,该数据库在我的单元测试环境中不存在。这就是为什么我更喜欢使用 H2 来运行单元测试的原因。
有没有正确的方法告诉 spring boot 使用 H2 进行测试,否则使用 Postgres ?
我不知道使用不同的 application.properties 文件(一个在 src/main/resources 中,另一个在 src/test/resources 中)是否可以解决问题。
您应该知道有多个类路径,例如:
当您使用时,依赖项将在运行时类路径和测试类路径<scope>runtime</scope>中可用,如文档所述:
此范围表示编译不需要依赖项,但执行需要依赖项。它位于运行时和测试类路径中,但不在编译类路径中。
这意味着即使您正在执行测试,如果您使用<scope>runtime</scope>.
您提到的解决方案,提供两个单独的解决方案application.properties是正确的选择。
在 中src/main/resources/application.properties,您可以像这样配置数据源:
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
Run Code Online (Sandbox Code Playgroud)
在 中src/test/resources/application.properties,您可以像这样配置数据源:
spring.datasource.url=jdbc:h2:mydatabase
Run Code Online (Sandbox Code Playgroud)
如果需要更细粒度的控制,可以使用 Spring 配置文件。例如,您可以使用名为“testdb”的配置文件,然后使用@ActiveProfiles("testdb").
现在您可以创建一个名为 的文件application-testdb.properties并添加设置测试数据库所需的属性。
| 归档时间: |
|
| 查看次数: |
4092 次 |
| 最近记录: |