Creating Test Fixtures easily with AutoFixture

February 22, 2011 | Unit Testing

When doing TDD there are many times that we use an ObjectMother class for test fixtures. In large domains, writing such classes can become tedious work. If we want random data things get even more complicated.

AutoFixture is a library written by Mark Seemann and can automate test fixture creation thereby saving time and making tests cleaner, faster, flexible and customizable.

Here is an example:

Unit Testing a class which contains an interface

Here I setup Moq to return a sequence of EventItem objects when I call the FindAll method. In the Setup method I pass a delegate where I use AutoFixture to create the sequence. What I really like here is that even though the EventItem contains interfaces AutoFixture can successfully create the sequence.

This is made possible by calling the Customize method and passing an instance of the AutoMoqCustomization type. This way we instruct AutoFixture to become an auto-mocking container and mock the interface types.

One of the class properties which is an interface

AutoFixture includes an assembly called Ploeh.AutoFixture.AutoMoq that uses Moq (which in turn Moq uses Castle DynamicProxy to generate proxies on the fly at runtime).

There is also Ploeh.AutoFixture.Xunit assembly for xUnit.net data theories.

All this stuff is amazing, and I would like to mention that the source code is perfectly written, contains a lot of patterns and best practises (like the Test Data Builder pattern). I am very happy with it.