Populate a database with TestContainers in a SpringBoot integration test

前端 未结 6 1859
自闭症患者
自闭症患者 2021-02-20 07:10

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.

How to do it?

         


        
6条回答
  •  暖寄归人
    2021-02-20 08:12

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

    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
    

    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.
    }
    

    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)

提交回复
热议问题