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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Leveraging Test Containers With Docker for Efficient Unit Testing
  • Docker + .NET APIs: Simplifying Deployment and Scaling
  • Integrating Spring Boot Microservices With MySQL Container Using Docker Desktop
  • Comparison of Various AI Code Generation Tools

Trending

  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  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 user avatar
David Guida
·
May. 13, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
15.8K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Leveraging Test Containers With Docker for Efficient Unit Testing
  • Docker + .NET APIs: Simplifying Deployment and Scaling
  • Integrating Spring Boot Microservices With MySQL Container Using Docker Desktop
  • Comparison of Various AI Code Generation Tools

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!