小编典典

嵌入式Postgres用于Spring Boot测试

spring-boot

我正在构建一个由Postgres支持的Spring
Boot应用程序,使用Flyway进行数据库迁移。我一直在解决无法在Postgres和嵌入式单元测试数据库(即使启用了Postgres兼容模式)中生成无法生成期望结果的迁移的问题。因此,我正在考虑将嵌入式Postgres用于单元测试。

我遇到了一个嵌入式的postgres实现,该实现看起来很有希望,但是并没有真正看到如何设置它以仅在Spring Boot的单元测试框架(用于测试Spring
Data存储库)中运行。如何使用上述工具或Postgres的另一嵌入式版本进行设置?


阅读 677

收藏
2020-05-30

共1个答案

小编典典

我是@MartinVolejnik提到的嵌入式数据库弹簧测试库的作者。我认为该库应该可以满足您的所有需求(PostgreSQL + Spring Boot + Flyway
+集成测试)。非常抱歉您遇到了麻烦,所以我创建了一个简单的演示应用程序,演示了该库与Spring Boot框架的结合使用。下面,我总结了您需要执行的基本步骤。

Maven配置

添加以下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配置

从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");
        });
    }
}
2020-05-30