A quick and dirty XUnit/AutoFixture MongoDb test harness

September 21, 2015 @ 6:37 am Posted to .Net, Testing by Antony Koch

As part of my new journey into outside-in testing I’ve – of course, for those that know me – looked into the tooling aspect. A part of that is implementing a MongoDB test harness injected via AutoFixture’s XUnit plugins.

As a quick side note, I think tooling is critical to elevating ones self from being a good developer to becoming a great one, as it removes the need to focus on anything other than writing production code. An example of this is my usage of NCrunch for continuous test execution. I can’t extol the benefits of not stopping to run all my tests enough, and it’s ben great to see the ongoing development of NCrunch since it’s free days.

Anyway – back to the point at hand.

I am building a MongoDb-backed application outside of my regular 9-5 engagement with my banking client, Investec, and needed a quick way to access the db in my tests. Avoiding ceremony was critical as I’m really into working on the production code as much as possible, not wasting time writing tests that will need to be rewritten when my implementation invariably changes as I learn more about the system I’m building. My app involves a twitter login, meaning everything I do from a database perspective is best served using the twitter UserId field. For cut one, I’ve come up with the following code, which I’ve added comments to for clarity:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Configuration;

using MongoDB.Bson;
using MongoDB.Driver;

namespace Amko.TwendingToday.Fast.Mongo
    public class MongoDbHarness : IDbHarness
        private IMongoDatabase _db;

        public MongoDbHarness()
            // Extract connection string from config
            var connectionString = ConfigurationManager.AppSettings[ServiceConstants.MongoDbUri];

            // Get a thread-safe client object by using a connection string
            var mongoClient = new MongoClient(connectionString);

            // Get a reference to a server object from the Mongo client object
            const string databaseName = "twitterapp"; // I've taken the real name out here to avoid giving spoilers :)

            // bootstrap our DB object
            _db = mongoClient.GetDatabase(databaseName);


        public async Task<BsonDocument> GetAsync(string collection, string userId)
            // Extract collection as a set of BsonDocument. The production code deals in
            // concrete domain objects, but for test purposes I'm loathe to spend time
            // building and rebuilding the ever changing domain in my test code. It
            // doesn't offer much over string indexes
            var coll = _db.GetCollection<BsonDocument>(collection);

            // build a filter for the get
            var filterDefinition = Builders<BsonDocument>.Filter.Eq("UserId", userId);

            // pull out the matching docs asynchronously
            var list = await coll.Find(filterDefinition).ToListAsync();

            // return the first one
            return list.FirstOrDefault();

    public interface IDbHarness
        Task<BsonDocument> GetAsync(string collection, string userId);

Although I’ve mentioned it in the above comments, I think it’s worth mentioning the point regarding the test domain and my decision not to create it. It’s common to build a copy of the domain object in test code to deserialise database into, or in worse cases to use the production models, but I decided against this. I feel that for it to be a true outside in test I should express my query against the resultant JSON from the DB as I might query the JSON in the real world, as it’s an extra verification step against how I think the system is working.

The injection of this is handled by AutoFixture using the following specimen builder:

    public class MongoHarnessSpecimenBuilder : ISpecimenBuilder
        public object Create(object request, ISpecimenContext context)
            var type = request as Type;

            if (type == null || type.IsPrimitive)
                return new NoSpecimen(request);

            if (type == typeof(IDbHarness))
                return new MongoDbHarness();

            return new NoSpecimen(request);

And this allows me to build my tests like this:

        public void TracksUserWhenTheyLogin(
            AuthController sut, 
            ActionResult actionResult,
            AuthenticatedUser user,
            IDbHarness dbHarness,
            DateTime now,
            string returnUrl)

I’ll dig out some resources for building the AutoFixture framework backing my AutomapData attribute and post them here later.

No comments (click to be first!)

What can we learn by refactoring without touching our unit tests? A converts’ explanation of outside-in testing.

August 26, 2015 @ 8:13 pm Posted to .Net, Mocking, Testing, Unit Testing by Antony Koch

Everywhere I’ve worked develops ‘features’. No great revelation there. However a feature is often, or at least ought to be, quite a small piece of functionality. A stripe of business value carved out of a larger solution. This stripe can be tested and released within a sprint while adding value to the business.

A lot of features can be expressed using a ‘happy path’: that is to say that there tends to be very few ways in which this feature can be executed without any exceptions thrown or any downstream entities not being found.

A typical scenario expressed in Gherkin takes the following form:

Given a context
When an action is perform
Then there is an outcome

Expanding upon this with a more real world set of scenarios:

Given an Amazon Prime customer
When the customer searches for goods
Then a Prime delivery option should be displayed

Given a non Amazon Prime customer
When the customer searches for goods
Then no prime delivery option should be displayed

Simple enough, right? Those 6 lines of text define everything we’re about to code up.

So of the time spent coding up, how much of it, in a TDD setting, is spent on unit tests? 50%? 75%? 75% of your time spent writing code that no user will touch.

Now let’s say the next feature comes along and we learn that our initial solution requires some refactoring. Where we once had one query and no commands we may now need nested queries and a single command along with, say, an extra integration point with a cloud service.

How much time do you need to spend rewriting those unit tests? Do you reconsider whether or not to refactor because of the burden of rewriting those tests? I know I have.

Now imaging you had no unit tests. Only acceptance, or black box, tests. Same web page. Same prime indicator. Same test. How much time do you spend writing tests when you refactor your underlying solution?

If you’ve got it right?


100% of your time writing production code. That’s what it’s supposed to be about, right? A bright idea hits you half way through your refactor. Your tests are still green. What’s the cost of experimenting?


You can commit what you have now – it’s working – and start tinkering. Your creativity starts to flow. Your repertoire of of enterprise patterns can come to the fore. Your factory factory loses its purpose: you don’t need interfaces just so you can mock, just so you can abstract.

This may seem somewhat preach, but I feel like this is the right way to do things.

More blog posts are to follow.

No comments (click to be first!)