MongoDB Developer
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right

Streamlining Java Application Development With MongoDB: A Comprehensive Guide to Using Testcontainers

Aasawari Sahasrabuddhe7 min read • Published May 25, 2024 • Updated May 28, 2024
Facebook Icontwitter iconlinkedin icon
Rate this article
The world of software development is a continuous cycle. We build, test, deploy, and iterate – striving to deliver high-quality applications. Within this software development lifecycle (SDLC), testing is crucial in ensuring our code functions as intended. There are two main types of tests we encounter:
  1. Unit testing: In this part, the intent is to check if the business logic for the code is working well and if no unexpected results are formed.
  2. Integration testing: In this part of testing, the developer assesses how different parts of the system interact with each other. They simulate real-world scenarios by integrating with external dependencies. While providing a more holistic view of application behavior, traditional integration tests can be cumbersome to set up and maintain due to the need for external resources like databases.
Testcontainers is an open-source framework for Java that leverages the power of Docker containers to streamline integration testing, by spinning up lightweight, throwaway instances of real dependencies within Docker containers for the duration of your test.
This tutorial will explore using Testcontainers with Java and Spring Boot, leveraging MongoDB as our database. We'll show you how to set up Testcontainers, integrate it into your project, and effectively use it to streamline your integration tests.
Let's get started.


  1. Java version 22 — download and install the latest JDK from the official Oracle website
  2. Maven version 3.9.6 — Download and install the latest version from the Maven official website
  3. Docker version 26.0.0 — Download and install Docker Desktop for your operating system from the official website

Getting started with Testcontainers

Why Testcontainers?

As a software developer, you navigate through every phase of the software development lifecycle during application development. Once the development phase is complete, the next critical stage involves writing test cases to verify the business logic of the application.
Whether your application is developed using vanilla Java or Spring Boot, you will typically write JUnit tests to ensure that the business logic functions correctly and meets the specified requirements. These tests are essential for validating the application's functionality and maintaining high-quality standards.
To test the complete functionality of your application, you are also required to perform integration testing. Integration testing is particularly important as it focuses on the interactions between different modules of the software. It detects interface issues and validates the functional relationships and data flow between combined units, ensuring they work together seamlessly. This is crucial for systems with multiple interconnected components, as it improves the overall reliability and stability of the application by ensuring that all parts integrate correctly and function as a unified whole.
Now, let's suppose your Java application uses MongoDB as its database. While writing your JUnits tests, what would you prefer?
  1. Testing your services with in-memory databases that may also be utilized by another module of the application?
  2. Testing the application with the database created locally only for the business logic to be tested?
As a part of the database optimization, you would choose the second option from the above.
Now, this is where Testcontainers would help achieve the second option.
Let us understand the concept of Testcontainers in the next section.

Introduction to Testcontainers

As quoted in the documentation for testcontainers:
Testcontainers for Java is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.
These containers are managed during test execution, ensuring a clean, isolated environment for each test or test suite. By leveraging Docker, Testcontainers allows developers to automate the setup and teardown of test dependencies, significantly simplifying the integration testing process.
As we have already discussed above, using Testcontainers gives you the advantage of using the database locally, reducing the load on the actual database used by the services.
Along with this, Testcontainers also helps in providing:
  1. Consistency: It ensures that the tests run in a consistent environment, regardless of the underlying infrastructure.
  2. Isolation: Each test can run in an isolated environment with its own set of dependencies.
  3. Up-to-date environments: This allows you to easily switch to different versions of dependencies by using different Docker images, which is particularly useful for testing compatibility with various versions of a database or service.

Working with Testcontainers

By now, you should have the theoretical knowledge about what Testcontainers is and why we should use it.
In this section of the article, we will discuss how Testcontainers can be used in Java and Spring Boot.
This will be divided into two sections:
  1. Testcontainers with Java
  2. Testcontainers with Spring Boot
The concept of Testcontainers remains the same irrespective of the framework being used, but these two sections will help you understand the application in both scenarios.
To begin using Testcontainers, you need to load the below dependency in your pom.xml file.

Testcontainers with vanilla Java

The test cases written in JUnits tests are executed in three stages with Testcontainers.
  1. Before tests: In this stage, the container is created, the database will be loaded, and collections will be created.
  2. During tests: This is the stage where the actual business logic of the application is tested.
  3. After tests: At this stage, the containers created in the first stage are destroyed and the resources are set free.
The code on how to use Testcontainers with Java is available in the GitHub repository.
In this code example, the JUnits test case is written to test a simple query to find five movie names that have IMDb ratings greater than seven.
The JUnits tests are written in the class and the below description will help you understand the code:
If you look at the code, it is divided in four parts:
  • Creating container: This will pull the mongo:7.0.0 docker image from Docker Hub and create the container.
  • Setup: The container is started and the example documents are inserted inside testCollection.
  • Actual tests: The actual test case for the business logic is implemented.
In the above code example, when the sample data is loaded, the resultDocuments will contain an empty list.
Next, in the try-catch section of the code, the cursor iterates through the results, adding each document to the resultDocuments list after printing it in JSON format to the console. After the iteration, the test asserts that exactly two documents were retrieved by checking the size of the resultDocuments list.
Additionally, for each document in the list, the test asserts that the title field is present and the _id field is absent. These assertions ensure that the query behaves as expected, retrieving the correct number of documents with the appropriate fields.
  • Stopping container: In this section, the connection is closed and the container is stopped. All business logic test cases should be written before this stage.
It is often confusing that the tests are created on the production database. But the advantage of using Testcontainers is that when you run the test class, the Docker image is loaded, the sample document is created, and the test cases are run all on this container. After the tests are completed, the container and connection are closed.
Now, let us try to understand how this logic can be implemented in the Spring Boot framework.

Testcontainers with Spring Boot

To write JUnits tests in a Spring Boot application, we will utilize an old GitHub repository that explains advanced aggregations using Spring Boot.
In this repository, you will see different REST APIs created that work on the sample_supplies.sales collection.
For this example, we will just utilize it to write test cases for the findAll() API.
The JUnits tests are similarly written in
  • Set up the container:
  • Insert data into the container:
  • Actual tests:
The testFindAll method validates the findAll function of SalesRepository. It checks if at least one sales record is returned if there's exactly one record, and if its attributes match expected values like store location, customer email, and the number of items purchased. This test ensures the correctness of the repository's retrieval function.
  • Stop the container:


Throughout this tutorial, we've demonstrated how to set up and use Testcontainers for integration testing with MongoDB in both a vanilla Java application and a Spring Boot application. We started by adding the necessary dependencies to our project, setting up the MongoDB container, and writing test cases to validate our business logic. Following these steps can achieve a more robust and maintainable testing setup.
If you liked this article and wish to practice more such content, we encourage you to visit the MongoDB Developer Centre. You can also visit our community forums for meaningful discussions and documentation for more learning.

Facebook Icontwitter iconlinkedin icon
Rate this article

Java - MongoDB Multi-Document ACID Transactions

Mar 01, 2024 | 10 min read

Microservices Architecture With Java, Spring, and MongoDB

Apr 17, 2024 | 4 min read

Create a Java REST API with Quarkus and Eclipse JNoSQL for MongoDB

Jan 30, 2024 | 6 min read

Introduction to Data Pagination With Quarkus and MongoDB: A Comprehensive Tutorial

Apr 25, 2024 | 7 min read
Table of Contents