MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs Menu
Docs Home
/ /

Integration Testing with Java and MongoDB Using Testcontainers

Testcontainers is a Java library that uses Docker containers to simplify integration testing. It creates temporary database instances that run during your tests and removes them automatically when tests finish.

This tutorial shows you how to use Testcontainers with MongoDB in both standard Java and Spring Boot applications.

Integration testing checks how different parts of your application work together. Unlike unit tests that validate individual pieces of code, integration tests verify that your code correctly interacts with external systems, such as databases or APIs.

Testcontainers performs the following steps when running tests:

  1. Before tests: Creates the container, loads the database, and creates collections

  2. During tests: Runs your test code

  3. After tests: Removes the container and frees resources

Tests that use Testcontainers run the same way on any computer and any operating system, and each test uses its own database instance. You can also switch between different database versions when necessary.

Before you begin, install the following:

  • Java version 22. To download, see the Oracle website.

  • Maven version 3.9.6. To download, see the Maven website.

  • Docker version 26.0.0. To download, see the Docker website.

You must also add the following dependencies to your application's pom.xml file:

<dependencyManagement>
<dependencies>
<!-- MongoDB Java Driver BOM -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Testcontainers BOM -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- JUnit BOM -->
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

The following example tests a query that finds movies with IMDb ratings above 7.0. To view the complete code, see the GitHub repository.

1

The following code creates a MongoDB container. The @Container annotation starts the container before tests and stops it after tests finish:

@Container
private static final MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:7.0.0");
2

The following code connects to the container and adds sample movies:

@BeforeAll
public void setup() {
String uri = mongoDBContainer.getConnectionString();
mongoClient = MongoClients.create(uri);
database = mongoClient.getDatabase("testdb");
collection = database.getCollection("testCollection");
// Insert sample data
Document doc1 = new Document("title", "Inception").append("imdb", new Document("rating", 8.8));
Document doc2 = new Document("title", "The Room").append("imdb", new Document("rating", 3.7));
Document doc3 = new Document("title", "The Dark Knight").append("imdb", new Document("rating", 9.0));
collection.insertMany(List.of(doc1, doc2, doc3));
}
3

The following code runs a query for movies with an imdb.rating field value greater than 7 and checks the results:

@Test
void testMoviesWithHighRating() {
List<Document> resultDocuments = new ArrayList<>();
try (MongoCursor<Document> cursor = collection.find(Filters.gt("imdb.rating", 7))
.projection(new Document("title", 1).append("_id", 0))
.iterator()) {
while (cursor.hasNext()) {
Document doc = cursor.next();
System.out.println(doc.toJson());
resultDocuments.add(doc);
}
}
assertEquals(2, resultDocuments.size());
for (Document doc : resultDocuments) {
assertTrue(doc.containsKey("title"));
assertFalse(doc.containsKey("_id"));
}
}

This test verifies the following:

  • The query returns exactly 2 documents

  • Each document has a title field

  • Each document excludes the _id field

The following example uses code from the Spring Boot MongoDB Aggregations repository to test a findAll() method.

1

The following code creates a MongoDB container:

@Container
public static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:7.0.0"));
2

The following code configures Spring Boot to use the test database:

@DynamicPropertySource
static void setProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
registry.add("spring.data.mongodb.database", () -> "testdb");
}
@BeforeAll
public static void setUpAll() {
String mongoUri = mongoDBContainer.getConnectionString();
mongoClient = MongoClients.create(mongoUri);
}
@BeforeEach
public void setUp() {
salesRepository.save(createMockSales());
}
private Sales createMockSales() {
Item item1 = new Item("Item1", Arrays.asList("Tag1", "Tag2"), new BigDecimal("19.99"), 2);
Item item2 = new Item("Item2", Arrays.asList("Tag3", "Tag4"), new BigDecimal("29.99"), 1);
List<Item> items = Arrays.asList(item1, item2);
Customer customer = new Customer("Male", 30, "customer@example.com", 5);
return new Sales(new ObjectId(), new Date(), items, "Store1", customer, true, "Online");
}
3

The following code tests the findAll() method:

@Test
public void testFindAll() {
List<Sales> salesList = salesRepository.findAll();
assertThat(salesList).isNotEmpty();
assertThat(salesList.size()).isEqualTo(1);
Sales sales = salesList.get(0);
assertThat(sales.getStoreLocation()).isEqualTo("Store1");
assertThat(sales.getCustomer().getEmail()).isEqualTo("customer@example.com");
assertThat(sales.getItems()).hasSize(2);
}

This test verifies the following:

  • The query returns exactly 2 documents

  • Each document has a title field

  • Each document excludes the _id field

Back

Quarkus with Panache and MongoDB

On this page