Integration Testing with MongoDB with MongoDB.Testing Library

I have put together a library, MongoDB.Testing, which makes it easy to stand up a MongoDB server, create a random database and clean up the resources afterwards. Here is how you can start using it.
5 December 2015
2 minutes read

Related Posts

Considering the applications we produce today (small, targeted, "micro" applications), I value integration tests way more than unit tests (along with acceptance tests). They provide much more realistic testing on your application with the only downside of being hard to pinpoint which part of your code is the problem when you have failures. I have been writing integration tests for the .NET based HTTP applications which use MongoDB as the data storage system on same parts and I pulled out a helper into library which makes it easy to stand up a MongoDB server, create a random database and clean up the resources afterwards. The library is called MongoDB.Testing and it’s on NuGet, GitHub. Usage is also pretty simple and there is also a a few samples I have put together.

Install the library into your testing project through NuGet:

Install-Package MongoDB.Testing -pre

Write a mongod.exe locator:

public class MongodExeLocator : IMongoExeLocator
{
    public string Locate()
    {
        return @"C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe";
    }
}

Finally, integrate this into your tests:

[Test]
public async Task HasEnoughRating_Should_Throw_When_The_User_Is_Not_Found()
{
    using (MongoTestServer server = MongoTestServer.Start(27017, new MongodExeLocator()))
    {
        // ARRANGE
        var collection = server.Database.GetCollection<UserEntity>("users");
        var service = new MyCounterService(collection);
        await collection.InsertOneAsync(new UserEntity
        {
            Id = ObjectId.GenerateNewId().ToString(),
            Name = "foo",
            Rating = 23
        });

        // ACT, ASSERT
        Assert.Throws<InvalidOperationException>(
            () => service.HasEnoughRating(ObjectId.GenerateNewId().ToString()));
    }
}

That’s basically all. MongoTestServer.Start will do the following for you:

  • Start a mongod instance and expose it through the specified port.
  • Creates a randomly named MongoDB database on the started instance and exposes it through the MongoTestServer instance returned from MongoTestServer.Start method.
  • Cleans up the resources, kills the mongod.exe instance when the MongoTestServer instance is disposed.

If you are doing a similar sort of testing with MongoDB, give this a shot. I want to improve this based on the needs. So, make sure to file issues and send some lovely pull requests.