You are on page 1of 5

We have multiple clients so multiples APIs that wants to use the application.

The solution is to create a copy of the database

If you’re not familiar with test containers visit the web site https://java.testcontainers.org/

Testcontainers is a library that supports JUnit tests providing lightweight instances of common
software like databases, web browsers, RabitMQ that can run in a Docker container.

Docker should be installed in your desktop

In our application, we need a module for postgres, it is indicated in the web site how to use it

https://java.testcontainers.org/modules/databases/postgres/

but before we have to integrate the test container to our application, if we want multiple
dependencies one for postgres, one for Kafka for example, we add the maven dependencies code to
pom.xml file
And load the maven changes , then install the postgres container (for that we go to modules>
databases and choose postgres

Without specifying the version of postgresql testcontainers

We then want to add the module for Junit5, we go to test framework integration and choose JUnit5

And remove the version and load the maven changes

For docker we go to spring initializr and choose Docker Compose Support dependency then explore
and copy the dependency code in our pom.xml

This dependency allows to create and run containers automatically (voir


https://spring.io/blog/2023/06/21/docker-compose-support-in-spring-boot-3-1 pour en savoir plus)

Configure Compose.yaml
Go to product service java test class

We add the @Testcontainers annotation the class

Dynamically populate the spring boot , we use a registry

Run to test our application

Add the repository

Then add a new product


(another method)

or we want to instanciate the attributes of the Product we put

@BeforeEach

void setUp(){

List<Product> products= List.of (new Product(id:1, name:"", etc.));

productRepository.saveAll(products);

and then show results by name for example

@Test

void shouldReturProductByName(){

Product product= productRepository.findByName("the name put bellow ");

assertThat(product).isNotNull();

Execute the test again

if it appears an error message with the second test then the table does not exist

in application.properties we put

Our repository test is ready

For the controller, we create an integration test for our controller now. We select our controller and
click on create test

Once creater we add this annotation to attibute a random port test on Tomcat and a test container
annotation to your class
Then add container

TestRestTemplate and RestTemplate are clients that are quite suitable for writing integration tests
and can handle communicating with HTTP APIs very well.

Run to see the result

You might also like