Spring Boot MySQL integration tests with Testcontainers

Spring Boot MySQL integration tests with Testcontainers

When it comes to writing database integration tests with Spring Boot, there are two options: an in-memory database or Testcontaienrs. As we already covered Testing Spring Data Repositories with H2 in-memory database, we shift the gear in this article and focus on writing Spring Boot MySQL integration tests with Testcontainers.

Introduction

Although utilizing an in-memory database is simple and easy, it poses some serious shortcomings. It does not support specific features of MySQL. For instance, the STRAIGHT_JOIN. Additionally, an in-memory database does not support migration scripts. As a result, many areas of the code cannot be tested, and the tests will not be similar to the production environment.

A better approach to writing integration tests for MySQL is using Testcontainers. With Testcontainers, we can run migration scripts and test any MySQL-specific features thoroughly and hassle-free.

In the rest of the article, we cover how to set up MySQL Testcontainers and write some tests with examples.

The code under the test

We have a User entity and repository that are used by the UserService. Our objective is to write some integration tests for the service layer.

The following is the code from the User, UserRepository, and UserService classes.

Add Testcontainers dependencies

To write Testcontainers tests, first, we need to add Testcontainers dependencies to the project as follows:

Writing Spring Boot MySQL integration tests with Testcontainers

Everything is ready now to write some awesome Testcontainers. The following code snippet is a fully functional repository test with Testcontainers.

Note that a test could use multiple containers, depending on the needs. In the above example, we had to run both Kafka and MySQL containers for tests to pass.

We utilized the @DynamicPropertySource to overwrite some properties on the fly. That is needed when the Testcontainers Docker port (JDBC connection) is generated randomly. It is better to keep it that way and avoid setting a predetermined port since it might conflict with another already running container.

Another crucial aspect of the above test is that it runs the Flyway migration scripts since we set the spring.flyway.enabled property to true. If you are interested to know more about Flyway, read this article.

Conclusion

In this article, we covered how to write some Spring Boot MySQL integration tests with Testcontainers. The sample project code is available on GitHub: https://github.com/kasramp/spring-kafka-test.

Inline/featured images credits