我是@MartinVolejnik提到的embedded-database-spring-test库的作者.我认为这个库应该满足你的所有需求(PostgreSQL+Spring Boot+Flyway+集成测试).我真的很抱歉您遇到了一些麻烦,所以我创建了一个simple demo app,演示了该库与Spring Boot框架的使用.下面我总结了一些你需要做的基本步骤.
Maven configuration
添加以下maven依赖项:
<dependency>
<groupId>io.zonky.test</groupId>
<artifactId>embedded-database-spring-test</artifactId>
<version>2.0.1</version>
<scope>test</scope>
</dependency>
Flyway configuration
将以下属性添加到应用程序配置中:
# 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
,这种优化没有效果.
Example
演示嵌入式数据库使用的测试类示例:
@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");
});
}
}