使用@DataJpaTest 的测试不使用嵌入式内存数据库

Tests with @DataJpaTest are not using embedded in-memory database

根据带有 @DataJpaTest 注释的 DataJpaTest documentation 测试,默认情况下将使用嵌入式内存数据库 (h2)

By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. They also use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource). The @AutoConfigureTestDatabase annotation can be used to override these settings.

但在我的情况下它没有发生,用 @DataJpaTest 注释的测试 class 正在加载 postgres 方言而不是使用 h2 方言。

下面是来自 main/resources

的 属性 文件
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/postgres?currentSchema=test
    username: test
    password: test
  jpa:
    database-platform: org.hibernate.dialect.PostgreSQLDialect

发生了什么

我发现 spring 不是从 main/resources 的 application.yml 文件中选择方言,而是尊重 @DataJpaTest 并使用 h2 方言。

解决方案

在尝试使用 jpa 属性的不同变体时,我发现只有当 database-platform 属性 出现在应用程序属性文件中时才会出现此问题。如果此 属性 被删除,那么它会加载测试用例的 h2 方言和主应用程序的 postgres 方言。

为什么?

这似乎是 spring 代码库中的一个错误,因为没有任何地方记录需要删除 database-platform 属性 以便 @DataJpaTest 使用 in-内存数据库。

根据 this documentation

,围绕 database-platform 属性 还有一个困惑

spring.jpa.database-platform

Name of the target database to operate on, auto-detected by default. Can be alternatively set using the "Database" enum.

似乎文档中还有一个错误,因为 spring.jpa.database-platform 只接受方言 class 作为值,其他枚举值都不起作用。