Saturday, March 12, 2016

How I Learned to Love Loosely Coupled Test Data

"Play fast and loose with faith? So jest with heaven,
Make such unconstant children of ourselves"
-- Shakespeare, King John
Act III, Scene I, Lines 242-243

For C# development, I love to use AutoFac!  I find that AutoFac allows me to change the design of my code without having to worry about decencies.  The last thing I want to have to do while refactoring my design is fix a bunch of broken unit tests.  Typically if find that I have to support hard coded test setup for the system under test, when I change the signature of the constructor I'll also need to change all the test setups related to the class (this is often the case in code in which I was not the original author).  This can become very annoying, since the test cases often do not really care about the setup of the system under test.

If you are using a decency injection framework like AutoFac you really need to pair the loose coupling of your production code decencies with loose coupling of the setup of your system under test.  Loose coupling of the setup of your system under test is exactly what a test fixture is for.

Personally I love AutoFixture for C# development!  AutoFixture does all the hard work of creating a test fixture for you, all you have to do is walk up to it and ask it for what you want.

If you are using AutoFac or some other IoC framework in your system under test, more likely than not, you are using a mocking framework like Moq or Rhino Mocks.  Well, AutoFixture has you covered by allowing you to use an auto mocking plugin for Moq, Rhino Mocks, or whatever.  By using auto mocking along with AutoFixture you are able to create a system under test with all the decencies already mocked out.

With AutoFixture creating the system under test for you, you can freely change the signature of your constructor for your system under test without the need to change any of the setup for the test cases!

Say we have the following:



The above is a fairly common example of C# application that I work with.

We see that we are testing using two different test classes, one using AutoFixture and one not.  If we uncomment out the ILog decency in the System class we would break the test setup in the test class ProgramTestsWithoutAutoFixture, but the test class SystemTestsWithAutoFixture would continue to work!  For such a simple example this might not matter, but with larger code bases this can become an issue.

By using AutoFixture with Moq we are pairing the same loosely coupling of the creation of our system under test with the loosely coupling we get for our decencies in our production code using AutoFac.  Truly one can say, AutoFac iff AutoFixture with Moq.