Testcontainers with Spring Boot and Java 11/17

Sameer
2 min readDec 7, 2021

What are Testcontainers?

Testcontainers is a JVM library that allows users to run and manage Docker images and control them from Java code. The integration test additionally runs external components as real Docker containers.

  • Databases — Run PostgreSQL as a Docker image
  • Mocked HTTP server — HTTP services by using MockServer or WireMock Docker images
  • Redis — run real Redis as a Docker image,
  • Message Brokers — RabbitMQ
  • AWS — S3, DynamoDB etc
  • Any other application that can be run as a Docker image

How to use?

  • Setup : Spring Boot and Junit 5
  • Dependency to testImplementation “org.testcontainers:postgresql:1.16.2” and testImplementation “org.testcontainers:junit-jupiter:1.16.2”
  • And then some wireing to start testcontainers and link them to the test context so that integration tests knows where to look for the containers.

Example Abstract Class for setup

How to write a test?

Advantages

  • Run Integration Tests offline.
  • You run tests against real components, PostgreSQL database instead of the H2 database.
  • You can mock AWS services.
  • Implementation and tests can be written by developers same time when raising a PR.
  • Multiple containers can be added and it’s consistent across all developer machines. Same versions etc and runs without any efforts with GitHub actions.

Disadvantages

  • The main limitation is, that containers cannot be reused between test classes.
  • Adding “one more” external dependency.
  • Takes a bit more time than usual to start a container, 4–5 seconds for Postgres VS 0.5 seconds for H2.
  • When running locally, local machine should be powerful enough too ;)
  • More RAM, More Power as multiple containers can be run.

References

https://www.baeldung.com/spring-boot-testcontainers-integration-test

Originally published at https://www.sameerkulkarni.de on December 7, 2021.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Sameer
Sameer

Written by Sameer

I am working as a Senior Software Engineer. I have 10+ years of Java Stack experience.

No responses yet

Write a response