How do you get Spring tests using @DataJpaTest
to use COMMIT
flush mode? This is not working for my Spock unit tests:
@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()
continues to return AUTO
.
This is with Spring Boot 2.2.2 with a dependency on spring-test:5.2.2.RELEASE.
I also have a configuration class:
@AutoConfigurationPackage
@SpringBootConfiguration
class MyConfiguration {
}
And src/test/resources/application.yml
(Gradle) appears to being read because certain configurations are being picked up (such as the datasource), but the spring.jpa.properties.org.hibernate.flushMode
property appears to be ignored from the config file while executing the @DataJpaTest
tests.
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
I've tried hacks like adding a @PostConstruct
in MyConfiguration
to call setFlushMode()
on the entityManager
but that doesn't work either. By the time the test is run, it has reverted back to AUTO
flush mode. (I'm guessing it reverts back to AUTO for every new session.)
I should have tried this before even posting the question, but it turns out this appears to be a Spring bug that has recently been fixed. I upgraded to Spring Boot v2.2.6 (which uses spring-test v5.2.5). When I posted my question, I was using Spring Boot v2.2.2. The upgrade from v2.2.2 to v2.2.6 has solved the problem. On v2.2.6, spring.jpa.properties.org.hibernate.flushMode
is not ignored in my test like it was with v2.2.2.