To make sure that tests are repeatable and isolated, it is a good practice to ensure that they always start with a clean state. In unit testing this could be mocking dependencies, or setting certain properties on objects. In integration testing it often means bringing the database to a well known state - usually erasing all the tables, and inserting the data that the integration tests expect.
In this short tutorial you'll see how to clean a database between integration tests. The recipe assumes that you use: relational database (like MySQL or PostgreSQL), Spring Boot, Flyway - for database migrations, JUnit 5.
Even if you don't use exactly these technologies, overall idea is quite generic, so I am sure you can adjust it to your needs.
You will also learn the following:
- why it is important to clear the database in integration tests
- how to clear the database using
JdbcTemplate
, Spring Data repositories and Flyway
- how to create custom JUnit 5 extension
- how to create JUnit 5 meta-annotations