我是@MartinVolejnik提到的嵌入式数据库弹簧测试库的作者。我认为该库应该可以满足您的所有需求(Postgresql + Spring Boot + Flyway +集成测试)。非常抱歉您遇到了麻烦,所以我创建了一个简单的演示应用程序,演示了该库与Spring Boot框架的结合使用。下面,我总结了您需要执行的基本步骤。
添加以下Maven依赖项:
<dependency>
<groupId>io.zonky.test</groupId>
<artifactId>embedded-database-spring-test</artifactId>
<version>1.5.2</version>
<scope>test</scope>
</dependency>
# Sets the schemas managed by Flyway -> change the xxx value to the name of your schema
# flyway.schemas=xxx // for spring boot 1.x.x
spring.flyway.schemas=xxx // for spring boot 2.x.x
此外,请确保您不使用org.flywaydb.test.junit.FlywayTestExecutionListener
。因为该库具有自己的测试执行监听器,可以优化数据库初始化,并且如果FlywayTestExecutionListener
应用,则此优化无效。
从Spring Boot 2开始,Hibernate和Postgres驱动程序存在兼容性问题。因此,您可能需要在应用程序配置中添加以下属性来解决此问题:
# Workaround for a compatibility issue of Spring Boot 2 with Hibernate and Postgres Driver
# See https://github.com/spring-projects/spring-boot/issues/12007
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureEmbeddedDatabase
public class SpringDataJpaAnnotationTest {
@Autowired
private PersonRepository personRepository;
@Test
public void testembeddedDatabase() {
Optional<Person> personOptional = personRepository.findById(1L);
assertThat(personOptional).hasValueSatisfying(person -> {
assertThat(person.getId()).isNotNull();
assertThat(person.getFirstName()).isEqualTo("Dave");
assertThat(person.getLastName()).isEqualTo("Syer");
});
}
}