【发布时间】: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