在SpringBoot集成测试中使用TestContainers填充数据库 [英] Populate a database with TestContainers in a SpringBoot integration test

查看:444
本文介绍了在SpringBoot集成测试中使用TestContainers填充数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试TestContainers,我想知道如何填充执行.sql文件的数据库以创建结构并添加一些行.

I am testing TestContainers and I would like to know how to populate a database executing a .sql file to create the structure and add some rows.

该怎么做?

@Rule
public PostgreSQLContainer postgres = new PostgreSQLContainer();

非常感谢

胡安·安东尼奥

推荐答案

使用Spring Boot时,我发现使用TestContainers的JDBC URL支持最简单.

When using Spring Boot, I find it easiest to use the JDBC URL support of TestContainers.

您可以创建一个application-integration-test.properties文件(通常在src/test/resources中使用以下内容:

You can create a application-integration-test.properties file (typically in src/test/resources with something like this:

spring.datasource.url=jdbc:tc:postgresql://localhost/myappdb
spring.datasource.driverClassName=org.testcontainers.jdbc.ContainerDatabaseDriver
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
# This line is only needed if you are using flyway for database migrations
# and not using the default location of `db/migration`
spring.flyway.locations=classpath:db/migration/postgresql

请注意JDBC网址中的:tc部分.

Note the :tc part in the JDBC url.

您现在可以像这样编写单元测试:

You can now write a unit test like this:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @ActiveProfiles("integration-test")
public class UserRepositoryIntegrationTest {
      @Autowired
      private MyObjectRepository repository;
      @PersistenceContext
      private EntityManager entityManager;
      @Autowired
      private JdbcTemplate template;

@Test
public void test() {
  // use your Spring Data repository, or the EntityManager or the JdbcTemplate to run your SQL and populate your database.
}

注意:这在构建API的实用指南中进行了解释结束于Spring Boot ,第7章(免责声明:我是本书的作者)

Note: This is explained in Practical Guide to Building an API Back End with Spring Boot, chapter 7 in more detail (Disclaimer: I am the author of the book)

这篇关于在SpringBoot集成测试中使用TestContainers填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆