Integration testing MongoDB with C# – More Fluent Syntax

Hi,

This is similar to my post around Azure Storage Integration testing just with a mongo twist. I’ve been working with mongo and didn’t really like the debugging workflow: Do something, start mongovue and manually check the item changed in the way you thought it would.

I’ve written a set of extensions to allow a nice set of declarative fluent assertions about the state of the MongoDB after an action has been performed.

 //assert
 mongoServer.AssertDatabaseExists(databaseName)
 .AssertCollectionExists<ExampleType>()
 .AssertCollectionItemCount(1)
 .AssertCollectionHasItemWithProperty<ExampleType>(item, x => x.MyProperty == 1);

Alongside this I’ve used an awesome nuget package from the guys at FireFunnel, which lets me spin up and work with an embedded Mongodb instance. I’ve written some simple methods to spin up the embedded instance and clean it in-between tests like so:

 [TestClass]
 public class ExampleTestClass
 {
  private static EmbeddedMongoDbServer mongoEmbedded;
  private static MongoClient mongoClient;
  private static MongoServer mongoServer;

 [ClassInitialize]
 public static void StartMongoEmbedded(TestContext cont)
 {
   mongoEmbedded = new EmbeddedMongoDbServer();
   mongoClient = mongoEmbedded.Client;
   mongoServer = mongoClient.GetServer();
 }

 [ClassCleanup]
 public static void ShutdownMongo()
 {
   mongoEmbedded.Dispose();
 }

 [TestInitialize]
 public void CleanMongo()
 {
   var databases = mongoServer.GetDatabaseNames();
   foreach (var databaseName in databases)
   {
     mongoServer.DropDatabase(databaseName);
   }
 }

...

Then I’ve also tweaked the extensions methods to give some nice actionable feedback when a test fails. For example when you create a query this is captured as an expression that is shown in the test output so you know exactly what query ran and can go about fixing it.

The source is up on Github, here. Let me know how you get on!

 

fluentMongo FluentMongoOutput

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: