Write custom annotation for testing SpringBoot application with real database

Matthias Schenk
2 min readJun 27, 2022

Testing application code requires different types of tests to verify the correct behavior (see https://martinfowler.com/articles/practical-test-pyramid.html).

Integration and acceptance tests play an important role in this mix. They verify that the application is correctly working with external components like mail service, database, message queue and so on.

Especially for tests which needs to verify that persistence to database is working as expected it is necessary to have the possibility to run against a test database. To ensure that the database in tests behaves the same way as in production the same type should be used. Don’t use In-Memory databases in this case (see: https://phauer.com/2017/dont-use-in-memory-databases-tests-h2/)

The Testcontainers framework (https://www.testcontainers.org/) offers an easy way for setup and run a real database inside a docker container which can be used as datasource for tests.

An first approach to integrate testcontainers in spring boot test can look like the following:

This test starts a docker container with mysql database which is used for all tests inside of the class.

But with every test class a new docker container with a new database is started. This leads to an increasing runtime of overall tests.

To solve this problem, it is possible to use one mysql database instance for all tests:

Use this class as base clase for all test classes. There is only one mysql instance used for all tests.

This can lead to problems if the tests expect an empty database or special kind of ids. 

To clear tables between each test can convert the base test functionality to a junit extension which can be used in combination with a test configuration

The last improvement of this version is the merging of the 3 annotations to a single one to improve readability.

see https://github.com/PoisonedYouth/RealDatabaseDemo.git for the sample project.

--

--