life is too short for a diary




TestContainers with Spring Boot

Tags: java spring boot

Testcontainers is a Java library that provides lightweight, disposable containers for running integration tests. It's a useful tool for testing applications that rely on external dependencies like databases or message queues.

Setup a demo Spring boot project

Gradle Dependencies

gradle terminologies

  1. testImplementation: This configuration is used for dependencies that are required only for the tests in your project. These dependencies will be available during the test compilation and execution phases, but they won't be included in the runtime classpath of your main application. This is useful when you have testing-specific libraries or frameworks that are not needed in the production code.

  2. compileOnly: This configuration is used for dependencies that are required only during the compilation phase but not at runtime. These dependencies will be available during the compilation of your main application code but won't be included in the final runtime classpath. This is often used for dependencies that are used for compile-time only, such as annotation processors or libraries used for generating code.

  3. implementation: This configuration is used for dependencies that are required during both the compilation and runtime phases of your application. These dependencies will be included in both the compilation classpath and the runtime classpath of your application. This is typically used for the main dependencies of your project that are required for the functionality of your application.

Define repository layer

Create repository/Customer.java

Create repository/CustomerRepository.java

Test using actual database

We can spin up database using docker

Also define application.yaml as

We also need to define a resources/schema.sql

We can write our test as

You can verify this by loging to your postgres database as

$ docker exec -it <CONTAINER_ID> -U user -d database -W

Test using TestContainers

Intead of running actual database everytime, it's much more convenient to use TestContainers


comments powered by Disqus