我正在使用 Spring Boot 开发一个微服务应用程序。 我的应用程序将使用 Postgres 数据库进行生产配置,并使用 H2 数据库进行 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>
在运行 mvn test 时,我可以看到 Spring Boot 默认选择的 postgres 数据库在我的单元测试环境中不存在。这就是为什么我更喜欢使用 H2 来运行单元测试的原因。
是否有正确的方法告诉 spring boot 使用 H2 进行测试,否则使用 Postgres?
我不知道使用不同的 application.properties 文件(一个在 src/main/resources 中,另一个在 src/test/resources 中)是否可以解决问题。
最佳答案
你应该知道有多个类路径,例如:
- 编译时类路径,
- 运行时类路径,
- 测试类路径。
当您使用 <scope>runtime</scope>
时,依赖项将在运行时类路径和测试类路径中可用,如the documentation所述:
This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
这意味着即使您正在执行测试,如果您使用 <scope>runtime</scope>
,Postgres 仍然会在您的类路径中。 .
您提到的解决方案,通过提供两个单独的 application.properties
是正确的选择。
在src/main/resources/application.properties
内,您可以像这样配置数据源:
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
在src/test/resources/application.properties
内,您可以像这样配置数据源:
spring.datasource.url=jdbc:h2:mydatabase
如果需要更细粒度的控制,可以使用 Spring 配置文件。例如,您可以使用名为“testdb”的配置文件,然后使用 @ActiveProfiles("testdb")
注释您的测试。 .
现在您可以创建一个名为 application-testdb.properties
的文件并添加设置测试数据库所需的属性。
关于java - 在 Spring Boot 的同一个 pom.xml 中管理 H2 和 Postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442400/