How You Can Use AutoFixture and AutoData To Drastically Improve Your Unit Tests - Part 1

If you have ever worked on a large project using TDD, or, you've worked on a big project where the team was aiming for a very high test coverage, then you'll understand the time and effort it take to write your tests set-up code.  In some instances, on complex classes, the set-up code alone has taken over 100 lines or more before I could crack on with the actual tests themselves.  If you have a class that has several other dependencies injected into it then before you know it, it can take more time to write your Moq set-up methods than it does your actual test code.  

Out of this set-up code, a large percentage of it is usually taken up by writing code to set-up default values for properties that you need to test, I mean how else can you test that a certain component works, without comparing an expecting value to something?

On a normal project, things get even more frustrating as time moves on.  After a period of time, requirements change and classes will need to be refactored to reflect these new requirements.  Simply changing the constructor signature, or adding a new dependency within an existing class, can result in a wasted morning of going through your unit tests set-up code and patching things up.  If you're in a rush, then your unit tests code can start to smell pretty badly, pretty quickly.

If you're like me, I prefer focusing my time and energy on writing new interesting features rather than writing boring boilerplate code and refactoring old unit tests.  So any tool or package that can help save me from this tedious hell makes me happy.  This is where AutoFixture comes in.  If you want to cut down on the amount of test set-up code you have to write and maintain, then read on.

What Is Autofixture?

AutoFixture really is a game changer when it comes to simplifying your unit test code. Autofixture can be thought of as a framework that will automatically pre-populate your class, interfaces and data-types with test-data without the need for you writing it yourself...  Auto Fakes on steriods!!!!  Below shows a very simple example of how to use AutoFixture:

        
        [Test]
        public void CreateRandomDate()
        {
            Fixture fixture = new Fixture();
            var aDate = fixture.Create<DateTime>();
        }
        
        [Test]
        public void CreateRandomInt()
        {
            Fixture fixture = new Fixture();
            var anInt = fixture.Create<int>();
        }

Pre-populating primitive data types is useful but not that exciting, Autofixture however, can go one step further and completely generate a whole class worth of test data, so say I had this class:

    public class MyClass
    {
        public string Data1 { get; set; }

        public int Data2 { get; set; }

        public DateTime Data3 { get; set; }
    }

You could use this code to get a completely populate object:

        public void PrepoluatedData()
        {
            var fixture = new Fixture().Customize(new AutoMoqCustomization());
            var objectWithPopulatedDaa = fixture.Create<MyClass>();
        }

If you have written a lot of unit tests in your life, then you can appreciate the amount of time it takes to simply write the code to pre-populate an object with some fake dummy data. Using Autofixture means you can literally use one line and get a fully populated object, instead of having to write a crap load of manually set-up code.

Using Autofixture within something like Resharper, means you can change and refactor your classes and, in a lot of instances, your unit tests will continue to run and pass OK without you needing to go back in and fixture them as the tests will automatically reflect your class changes... it really is a game changer!

How To Install Autofixture?

Autofixture is free to use via Nuget, there are a number of different associated packages for it depending on what frameworks you're using. These additional packages cover everything from the test suite you're using, like a NUnit, xUnit add-on, to what mocking framework you're using like Moq, RhineMocks etc..


I tend to favour NUnit and Moq and as you can see above, I simply add in the packages relevant to my project and you're ready to rock.

Wait -There's More To Autofixture

On top of auto-populated objects you can also use Autofixture to help automate your tests.  If you use dependency injection with guards, then you can create a simple helper method to automatically check for nulls for you, further minimising the amount of test code you need to write, read here for more information on that.

You can also further reduce your AutoFixture code above by auto-inserting pre-populated test data into your tests like so:

        [Test, AutoData]
        public void PrePopulateClass(MyClass myClass)
        {
            var prePopulateClass = myClass;
        }

Using this technique means that within our unit tests we only need to worry about the actual logic and leave the arrange part to Autofixture.  Offloading the arrange config, greatly reduces the amount of unit test maintenance that needs to be done.

NOTE: If like me, you use Moq and NUnits, if you try and run the code above you may get this error 'AutoData error - No arguments were provided '. To get AutoData working in this scenario, you need to jump through a few more hoops, which is covered in this tutorial.

Conclusion

If you write a lot of tests then I'm hoping you can appreciate how much time Autofixture can save you. I've worked on projects without Autofixture and the amount of boilerplate test code we had to write became a maintenance nightmare very quickly. Updating the test code to work with the new code changes often took longer than making the change.

Using Autofixture will greatly simplfy your unit tests code base and consequently make unit test maintenance easier to manage. If you're not using Autofixture, then my challenge to you is add it within your project now. I bet that within 30 minutes, you'll be able to make at least one of your test classes simpler, easier to read and a lot more easier to maintain in the future, enjoy!

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top