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:
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.