AutoMocking Container

At work I am lucky enough to work with a few bright chaps (sadly some of them are a lot youger than me, which is making me question my existence :-( , but on the other hand it is always good to learn new things). One of those new things for me happened the other [&#8230;]

At work I am lucky enough to work with a few bright chaps (sadly some of them are a lot youger than me, which is making me question my existence , but on the other hand it is always good to learn new things).

One of those new things for me happened the other day, where this dude at work showed me MSpec for TDD/BDD, and I have to say it was pretty awesome. The thing that I liked the most was the “AutoMocking” feature

So what is this “AutoMocking” that I am talking about, and why is it cool? Well quite simply it eliviates the brittle relationship with code and tests in their infancy, and allows tests to create constructor injection parameters automatically

I should point out that this pattern really suits new code bases, that may still be a bit in flux, it is not really that much use for well established code bases that have been around and settled for a while

It is also worth noting that this pattern can be used with code that doesn’t use any IOC/dependency injection at all, it is purely a testing concern

This should immediately ring alarm bells that your existing test cases will now break, but what can we do about it? This is where “AutoMocking” can help. Let us take a look at this shall we.

So the first step is to decide on a nice IOC container that you think is fit for the job. For me this is Castle Windsor. So that is that decision made, so what do we need to do now that we have made that decision? Well all we really need to do is get it to automatically create our Mocks for us. SO what does that look like? Well for me it looks like this

With that all in place I can now write non brittle code, that will get the object I want to test from the IOC container, where all its dependencies will try to be satified by the automocking IOC container. So my test case now looks like this