DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • What Actually Breaks During Large-Scale S/4HANA Conversions (And How to Prevent It)
  • A Guide for Deploying .NET 10 Applications Using Docker's New Workflow
  • Leveraging Test Containers With Docker for Efficient Unit Testing
  • Docker + .NET APIs: Simplifying Deployment and Scaling

Trending

  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing
  • A Software Factory on Kubernetes: Gemini Builds, jev Decides (Genkit + senro in Go)

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Write Integration Tests on MongoDB With .NET Core and Docker

Write Integration Tests on MongoDB With .NET Core and Docker

In this post, we're going to explore a simple but effective way to write integration tests on MongoDB using .NET Core and Docker.

By 
David Guida
·
May. 13, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
16.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Hi all! In this post, we’re going to explore a simple but effective way to write integration tests on MongoDB using .NET Core and Docker.

A while ago I wrote a small series about Unit Testing on MongoDB. A lot has changed since then, and I also received a few requests to add more details. To be fair, I am not even that happy now with those articles. I bet it’s the same feeling we’re all experiencing when we look at the code we wrote in the past.

Let’s just say that when it comes to testing, we should all follow the Test Pyramid. And when it comes to the persistence layer, I think the best way is to always “hit the metal” and check if a real DB is happy with the code we wrote.

For example, EntityFramework exposes an In-Memory provider that can be used to write tests. It’s a valuable tool, but it doesn’t guarantee that the DbContext configuration and the Entities mapping is 100% valid.

For that, the only thing you can do is bite the bullet, connect to a DB instance, and run few statements.

Now, I wrote already how to write integration tests in a CI/CD pipeline. We are going to use the exact same approach, but for MongoDB instead.

All the code is as usual available on GitHub, feel free to take a look before moving on.

As you can see, I have added a docker-compose configuration to the root. The first step before launching the test suite is to run docker-compose up . It will download the official MongoDB image if you don’t have it already, and spin up the DB server.

The instance will be available on localhost, port 27097, and this is where we’re pointing our code.

Adding a Docker configuration is something that I’ve been recently doing for basically all my projects: Devs should be able to spin up all the required infrastructure with 1-2 console commands, without spending too much time wondering why things don’t work.

This doesn’t mean we shouldn’t be aware of what is going on under the hood. All the opposite. But everything Ops-related should absolutely be transparent to Devs and bring little to 0 noise.

Personally, I prefer to focus on writing the application code and be sure all the client’s features are implemented correctly, rather than dwelling into the labyrinths of unreachable networks and unmountable volumes and what not.

Going back to the tests, the XUnit Fixture is basically the heart of the sample: 

C#
 




x


 
1
public class DbFixture : IDisposable
2
{
3
    public DbFixture()
4
    {
5
        var config = new ConfigurationBuilder()
6
            .AddJsonFile("appsettings.json")
7
            .Build();
8

          
9
        var connString = config.GetConnectionString("db");
10
        var dbName = $"test_db_{Guid.NewGuid()}";
11

          
12
        this.DbContextSettings = new MongoDbContextSettings(connString, dbName);
13
        this.DbContext = new MongoDbContext(this.DbContextSettings);
14
    }
15

          
16
    public MongoDbContextSettings DbContextSettings { get; }
17
    public MongoDbContext DbContext { get; }
18

          
19
    public void Dispose()
20
    {
21
        var client = new MongoClient(this.DbContextSettings.ConnectionString);
22
        client.DropDatabase(this.DbContextSettings.DatabaseName);
23
    }
24
}



Let’s see what’s happening here:

  1. It loads the connection string from the configuration file
  2. Generates a random DB name
  3. Spins up the MongoDbContext
  4. Ensures that the DB is dropped at the end of the suite

Few words on Point 2 and 4:

  • Point 2 is extremely important to ensure that every execution is isolated. We don’t want test data created for a class messing with tests in another file.
  • The Dispose() method gives guarantee for Point 4. Once a test suite is executed there’s no point keeping the DB around.

That’s all for today. With COVID-19 still around, stay home, stay healthy, take some vitamins, and code!

unit test MongoDB Docker (software) Integration .NET

Opinions expressed by DZone contributors are their own.

Related

  • What Actually Breaks During Large-Scale S/4HANA Conversions (And How to Prevent It)
  • A Guide for Deploying .NET 10 Applications Using Docker's New Workflow
  • Leveraging Test Containers With Docker for Efficient Unit Testing
  • Docker + .NET APIs: Simplifying Deployment and Scaling

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook