Populate a database with TestContainers in a SpringBoot integration test

前端 未结 6 1861
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-20 07:52

    Spring framework provides the ability to execute SQL scripts for test suites or for a test unit. For example:

    @Test
    @Sql({"/test-schema.sql", "/test-user-data.sql"}) 
    public void userTest {
       // execute code that relies on the test schema and test data
    }
    

    Here's the documentation.

    You can also take a look at Spring Test DBUnit which provides annotations to populate your database for a test unit. It uses XML dataset files.

    @Test
    @DatabaseSetup(value = "insert.xml")
    @DatabaseTearDown(value = "insert.xml")
    public void testInsert() throws Exception {
         // Inserts "insert.xml" before test execution
         // Remove "insert.xml" after test execution
    }
    

    Also, you can take a look at DbSetup, which provides a java fluent DSL to populate your database.

提交回复
热议问题