Search code examples
c#-4.0mongodbmoqmongodb-.net-driver

How do I mock MongoDB objects to test my data models?


I'm using the following logic (MOQ) to attempt to mock out the MongoDB csharp driver objects:

var svr = new Mock<MongoServer>(new MongoServerSettings());
var db = new Mock<MongoDatabase>(svr.Object, new MongoDatabaseSettings("hf_test", 
new MongoCredentials("hf_test", "hf_pass"), GuidRepresentation.Standard,
                                                 SafeMode.False, false));

When I call db.Object, MOQ attempts to create an instance of my mock MongoDatabase, but it fails with a null-reference exception.

Note: I'm thinking of making an IMongoCollection interface, and wrapping MongoCollection in an instance of it. Then, I can simply mock that out... But that seems like a whole lot of unnecessary work.


Solution

  • I ended up creating my own interfaces which were basically shallow wrappers on top of the Mongo objects. I can mock these interfaces out, and at least test that the proper indices and filters are in my DAL queries.