在使用 @DataJpaTest 时更改 Spring 引导测试中的刷新模式?
Change flush mode in Spring Boot tests when @DataJpaTest in use?
如何使用 @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()
继续 return AUTO
。
这是 Spring Boot 2.2.2 依赖于 spring-test:5.2.2.RELEASE.
我也有配置class:
@AutoConfigurationPackage
@SpringBootConfiguration
class MyConfiguration {
}
和 src/test/resources/application.yml
(Gradle) 似乎正在读取,因为正在获取某些配置(例如数据源),但 spring.jpa.properties.org.hibernate.flushMode
属性 似乎在执行 @DataJpaTest
测试时从配置文件中忽略。
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 最近已修复的错误。我升级到 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 那样被忽略。
如何使用 @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()
继续 return AUTO
。
这是 Spring Boot 2.2.2 依赖于 spring-test:5.2.2.RELEASE.
我也有配置class:
@AutoConfigurationPackage
@SpringBootConfiguration
class MyConfiguration {
}
和 src/test/resources/application.yml
(Gradle) 似乎正在读取,因为正在获取某些配置(例如数据源),但 spring.jpa.properties.org.hibernate.flushMode
属性 似乎在执行 @DataJpaTest
测试时从配置文件中忽略。
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 最近已修复的错误。我升级到 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 那样被忽略。