微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于Spring Boot Tests的嵌入式Postgres

我正在构建一个由Postgres支持Spring Boot应用程序,使用Flyway进行数据库迁移.我一直在遇到无法产生迁移的问题,这些迁移在Postgres和嵌入式单元测试数据库中都会产生预期的结果(即使启用了Postgres兼容模式).所以我正在考虑使用嵌入式Postgres进行单元测试.

我遇到了看起来很有希望的an embedded postgres实现,但是没有真正看到如何将其设置为仅在Spring Boot的单元测试框架中运行(用于测试Spring Data存储库).如何使用上述工具或Postgres的替代嵌入版本来设置它?

解决方法:

我是@MartinVolejnik提到的embedded-database-spring-test库的作者.我认为该库应该满足您的所有需求(Postgresql Spring Boot Flyway集成测试).我真的很抱歉你遇到了麻烦,所以我创建了一个simple demo app,它演示了如何将库与Spring Boot框架一起使用.下面我总结了您需要做的基本步骤.

Maven配置

添加以下maven依赖项:

<dependency>
    <groupId>io.zonky.test</groupId>
    <artifactId>embedded-database-spring-test</artifactId>
    <version>1.5.0</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 Driver存在兼容性问题.因此,您可能需要将以下属性添加到应用程序配置中以修复该问题:

# 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");
        });
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐