Search code examples
spring-bootliquibasetestcontainers

Reset database between tests when using Testcontainers and Liquibase


If I am using a singleton database container in my integration tests, how can I make sure the database is in a clean state (no data) before each test? The codebase is using Liquibase for data migrations.


Solution

  • If you want to delete all rows inside your database after/before each test, you can:

    1. Use @Transactional for your tests and Spring will rollback the transaction after each test
    2. Use the JdbcTemplate/YourEntityRepository (Spring Data JPA Repositories) and delete them with a DELETE SQL query (JdbcTemplate) or .deleteAll() (Spring Data JPA repositories) as part of JUnit Jupiters @BeforeEach/@AfterEach

    Your applied DDL scripts (CREATE) from Liquibase will remain and each test starts with a valid schema.