您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

嵌入式Postgres用于Spring Boot测试

嵌入式Postgres用于Spring Boot测试

我是@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");
        });
    }
}
Postgres 2022/1/1 18:21:20 有339人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶