【问题标题】:Change flush mode in Spring Boot tests when @DataJpaTest in use?在使用 @DataJpaTest 时更改 Spring Boot 测试中的刷新模式?
【发布时间】:2020-08-13 22:27:56
【问题描述】:

如何使用 @DataJpaTest 进行 Spring 测试以使用 COMMIT 刷新模式?这不适用于我的 Spock 单元测试:

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@DataJpaTest(properties = "spring.jpa.properties.org.hibernate.flushMode=COMMIT")
class MyJpaTestSpec extends Specification {
    @Autowired
    EntityManager entityManager

    def "test flush mode"() {
        expect:
        // confirming that flushMode is still AUTO even though I configured COMMIT
        entityManager.flushMode == FlushModeType.AUTO
    }
}

entityManager.getFlushMode() 继续返回AUTO

这是依赖于 spring-test:5.2.2.RELEASE 的 Spring Boot 2.2.2。

我还有一个配置类:

@AutoConfigurationPackage
@SpringBootConfiguration
class MyConfiguration {
}

并且src/test/resources/application.yml (Gradle) 似乎已被读取,因为正在获取某些配置(例如数据源),但在执行 @DataJpaTest 测试时,配置文件中似乎忽略了 spring.jpa.properties.org.hibernate.flushMode 属性。

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1
    username: sa
    password: sa
  jpa:
    # seems to be ignored for @DataJpaTests
    properties:
        org.hibernate.flushMode: COMMIT

我尝试过一些技巧,比如在MyConfiguration 中添加@PostConstruct 以在entityManager 上调用setFlushMode(),但这也不起作用。到运行测试时,它已恢复到AUTO 刷新模式。 (我猜它会在每次新会话时恢复为 AUTO。)

【问题讨论】:

    标签: spring unit-testing jpa spring-boot-test


    【解决方案1】:

    我应该在发布问题之前就尝试过,但事实证明这似乎是最近修复的 Spring 错误。我升级到 Spring Boot v2.2.6(使用 spring-test v5.2.5)。当我发布我的问题时,我使用的是 Spring Boot v2.2.2。从 v2.2.2 升级到 v2.2.6 解决了这个问题。在 v2.2.6 上,spring.jpa.properties.org.hibernate.flushMode 在我的测试中不会像 v2.2.2 一样被忽略。

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 2018-01-25
      • 2019-03-28
      • 2018-07-17
      • 2018-10-26
      • 1970-01-01
      • 2018-01-18
      • 2018-03-01
      相关资源
      最近更新 更多