Using Testcontainers with MongoDB
When creating integration tests that depend on MongoDB, we have two options: using an in-memory database server embedded in our application or using Testcontainers. The in-memory database server can have slight differences from our production system. For that reason, I recommend using Testcontainers; it allows you to use a real MongoDB database hosted in Docker with all features enabled.
In this recipe, we’ll learn how to set up a MongoDB Testcontainer and how to execute some initialization scripts so that we can insert test data into the database.
Getting ready
Executing Testcontainers requires a Docker-API compatible runtime. You can install Docker by following the instructions on the official web page: https://www.docker.com/products/docker-desktop/.
In this recipe, we’ll add tests for the project we created in the Connecting your application to MongoDB recipe. I’ve created a working version of that recipe in case...