# Wednesday, January 27, 2010

AutoFixture 1.0 is now available on the CodePlex site! Compared to Release Candidate 2 there are no changes.

The 1.0 release page has more details about this particular release, but essentially this is RC2 promoted to release status.

It's been almost a year since I started development on AutoFixture and I must say that it has been an exciting and fulfilling experience! The API has evolved, but has turned out to be surprisingly flexible, yet robust. I even had some positive surprises along the way as it dawned on me that I could do new fancy things I hadn't originally considered.

If you use the Likeness feature (of which I have yet to write), you will run into this bug in Visual Studio. The bug is only in IntelliSense, so any code using Likeness will compile and work just fine.

While this release marks the end of AutoFixture's initial days, it also marks the beginning of AutoFixture 2.0. I already have lots of plans for making it even more extensible and powerful, as well as plans for utility libraries that integrate with, say, Moq or Rhino Mocks. It's going to be an exciting new voyage!

posted on Wednesday, January 27, 2010 11:54:58 PM (Romance Standard Time, UTC+01:00)  #    Comments [4] Trackback
# Wednesday, January 20, 2010

AutoFixture 1.0 Release Candidate 2 is now available on the CodePlex site! Compared to Release Candidate 1 there are very few changes, but the test period uncovered the need for a few extra methods on a recent addition to the library. RC2 contains these additional methods.

This resets the clock for the Release Candidate trial period. Key users have a chance to veto this release until a week from now. If no-one complains within that period, we will promote RC2 to version 1.0.

The RC2 release page has more details about this particular release.

posted on Wednesday, January 20, 2010 11:59:39 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, January 13, 2010

AutoFixture 1.0 Release Candidate 1 is now available on the CodePlex site! AutoFixture is now almost ten months old and has seen extensive use internally in Safewhere during most of this time. It has proven to be very stable, expressive and generally a delight to use.

If all goes well, the Release Candidate period will be short. Key users have a chance to veto the this version, but if no-one complains within a week from now, we will promote RC1 to version 1.0.

The RC1 release page has more detail about this particular release.

posted on Wednesday, January 13, 2010 11:48:13 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, January 04, 2010

In a previous post I described how AutoFixture's Do method can let you invoke commands on your SUT with Dummy values for the parameters you don't care about.

The Get method is the equivalent method you can use when the member you are invoking returns a value. In other words: if you want to call a method on your SUT to get a value, but you don't want the hassle of coming up with values you don't care about, you can let the Get method supply those values for you.

In today's example I will demonstrate a unit test that verifies the behavior of a custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't really matter. The point is that a ModelBinder must implement the IModelBinder interface that defines a single method:

object BindModel(ControllerContext controllerContext,

    ModelBindingContext bindingContext);

In many cases we don't care about one or the other of these parameters, but we still need to supply them when unit testing.

The example is a bit more complex than some of my other sample code, but once in a while I like to provide you with slightly more realistic AutoFixture examples. Still, it's only 10 lines of code, but it looks like a lot more because I have wrapped several of the lines so that the code is still readable on small screens.

[TestMethod]

public void BindModelWillReturnCorrectResult()

{

    // Fixture setup

    var fixture = new Fixture();

    fixture.Customize<ControllerContext>(ob =>

        ob.OmitAutoProperties());

 

    var value = fixture.CreateAnonymous("Value");

    var bindingContext = new ModelBindingContext();

    bindingContext.ValueProvider =

        new Dictionary<string, ValueProviderResult>();

    bindingContext.ValueProvider["MyValue"] =

        new ValueProviderResult(value, value,

            CultureInfo.CurrentCulture);

 

    var expectedResult =

        new string(value.Reverse().ToArray());

    var sut = fixture.CreateAnonymous<MyModelBinder>();

    // Exercise system

    var result = fixture.Get((ControllerContext cc) =>

        sut.BindModel(cc, bindingContext));

    // Verify outcome

    Assert.AreEqual(expectedResult, result, "BindModel");

    // Teardown

}

The first part simply creates the Fixture object and customizes it to disable AutoProperties for all ControllerContext instances (otherwise we would have to set up a lot of Test Doubles for such properties as HttpContext, RequestContext etc.).

The next part of the test sets up a ModelBindingContext instance that will be used to exercise the SUT. In this test case, the bindingContext parameter of the BindModel method is important, so I explicitly set that up. On the other hand, I don't care about the controllerContext parameter in this test case, so I ask the Get method to take care of that for me:

var result = fixture.Get((ControllerContext cc) =>

    sut.BindModel(cc, bindingContext));

The Get method creates a Dummy value for the ControllerContext, whereas I can still use the outer variable bindingContext to call the BindModel method. The return value of the BindModel method is returned to the result variable by the Get method.

Like the Do methods, the Get methods are generic methods. The one invoked in this example has this signature:

public TResult Get<T, TResult>(Func<T, TResult> function);

There are also overloads that works with the versions of the Func delegate that takes two, three and four parameters.

As the Do methods, the Get methods are convenience methods that let you concentrate on writing the test code you care about while it takes care of all the rest. You could have written a slightly more complex version that didn't use Get but instead used the CreateAnonymous method to create an Anonymous Variable for the ControllerContext, but this way is slightly more succinct.

posted on Monday, January 04, 2010 9:53:24 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, December 05, 2009

A reader asked me how AutoFixture can deal with arrays as fields on a class. More specifically, given a class like MyClassA, how can AutoFixture assign a proper array with initialized values to Items?

public class MyClassA
{
    public MyClassB[] Items;
    public MyClassC C;
    public MyClassD D;
}

Ignoring the bad practice of publicly exposing fields, the main problem is that AutoFixture has no inherent understanding of arrays, so if we try to create a new instance of MyClassA by invoking the CreateAnonymous method, we would end up with Items being an array of nulls.

Obviously we want a populated array instead. There are at least a couple of ways to reach this goal.

The simplest is just to create it and modify it afterwards:

var mc = fixture.CreateAnonymous<MyClassA>();
mc.Items = fixture.CreateMany<MyClassB>().ToArray();

Although the CreateAnomymous method will assign an unitialized array, we immediately overwrite the value with an initialized array. The CreateMany method returns an IEnumerable<MyClassB> on which we can use the ToArray extension method to create an array.

The next option is to do almost the same thing, but as a single operation:

var mc = fixture.Build<MyClassA>()
    .With(x => x.Items, 
        fixture.CreateMany<MyClassB>().ToArray())
    .CreateAnonymous();

Besides the different syntax and the lower semicolon count, the biggest difference is that in this case the Items field is never assigned an unitialized array because the With method ensures that the specified value is assigned immediately.

If you get tired of writing this Builder sequence every time you want to create a new MyClassA instance, you can Customize the Fixture:

fixture.Customize<MyClassA>(ob =>
    ob.With(x => x.Items, 
        fixture.CreateMany<MyClassB>().ToArray()));

With this customization, every time we invoke

var mc = fixture.CreateAnonymous<MyClassA>();

we will get an instance of MyClassA with a properly initialized Items array.

I hope you find one or more of these methods useful.

posted on Saturday, December 05, 2009 1:41:45 AM (Romance Standard Time, UTC+01:00)  #    Comments [1] Trackback
# Thursday, November 26, 2009

In unit testing an important step is to exercise the SUT. The member you want to invoke is often a method that takes one or more parameters, but in some test cases you don't care about the values of those parameters – you just want to invoke the method.

You can always make up one or more Dummy parameters and pass them to the method in question, but you could also use one of AutoFixture's Do convenience methods. There are several overloads that all take delegates that specify the action in question while providing you with Dummies of any parameters you don't care about.

A good example is WPF's ICommand interface. The most prevalent method is the Execute method that takes a single parameter parameter:

void Execute(object parameter);

Most of the time we don't really care about the parameter because we only care that the command was invoked. However, we still need to supply a value for the parameter when we unit test our ICommand implementations. Obviously, we could just pass in a new System.Object every time, but why not let AutoFixture take care of that for us?

(You may think that new'ing up a System.Object is something you can easily do yourself, but imagine other APIs that require much more complex input parameters, and you should begin to see the potential.)

Here's a state-based unit test that verifies that the Message property of the MyViewModel class has the correct value after the FooCommand has been invoked:

[TestMethod]

public void FooWillUpdateMessage()

{

    // Fixture setup

    var fixture = new Fixture();

    var sut = fixture.CreateAnonymous<MyViewModel>();

    // Exercise system

    fixture.Do((object parameter) =>

        sut.FooCommand.Execute(parameter));

    // Verify outcome

    Assert.AreEqual("Foo", sut.Message, "Message");

    // Teardown

}

Notice how the Do method takes an Action<object> to specify the method to invoke. AutoFixture automatically supplies an instance for the parameter parameter using the same engine to create Anonymous variables that it uses for everything else.

The Do method in question is really a generic method with this signature:

public void Do<T>(Action<T> action);

There are also overloads that take two, three or four input parameters, corresponding to the available Action types available in the BCL.

These methods are simply convenience methods that allow you to express your test code more succinctly than you would otherwise have been able to do.

posted on Thursday, November 26, 2009 10:23:46 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, November 07, 2009

The following feature suggestion was recently posted in the AutoFixture Issue Tracker board:

"We're using AutoFixture to create random rows of data in our DB. A lot of times though, it creates strings that are too long for the database columns. It would be nice if the .With<string> method had an overload that took in a min/max length. We want the random data, but capped at a limit.

"fixture.Build<MyObject>.With(x = x.MyString, 0, 100);

"As an aside, this is for a project that uses Nhibernate and Fluent Nhibernate, which has these lengths already defined. I would be nice if AutoFixture could automatically pick up on that somehow."

I think such an feature is an excellent idea, but I don't think I will include in AutoFixture. Why not?

So far, I have kept the AutoFixture API pretty clean and very generic, and it is my belief that this is one of the main reasons it is so expressive and flexible. There are no methods that only work on specific types (such as strings), and I am reluctant to introduce them now.

In the last six months, I have identified a lot of specialized usage idioms that I would love to package into a reusable library, but I think that they will pollute the core AutoFixture API, so I'm going to put those in one or more optional 'add-on' libraries.

The ability to define strings that are constrained on length could be one such feature, but rather than wait for a helper library, I will show you have you can implement such a method yourself.

The first thing we need is a method that can create anonymous strings given length constraints. One possible implementation is this ConstrainedStringGenerator class:

public class ConstrainedStringGenerator
{
    private readonly int minimumLength;
    private readonly int maximumLength;
 
    public ConstrainedStringGenerator(int minimumLength, 
        int maximumLength)
    {
        if (maximumLength < 0)
        {
            throw new ArgumentOutOfRangeException("...");
        }
        if (minimumLength > maximumLength)
        {
            throw new ArgumentOutOfRangeException("...");
        }
 
        this.minimumLength = minimumLength;
        this.maximumLength = maximumLength;
    }
 
    public string CreateaAnonymous(string seed)
    {
        var s = string.Empty;
        while (s.Length < this.minimumLength)
        {
            s += GuidStringGenerator.CreateAnonymous(seed);
        }
        if (s.Length > this.maximumLength)
        {
            s = s.Substring(0, this.maximumLength);
        }
        return s;
    }
}

The CreateAnonymous method uses AutoFixture's GuidStringGenerator class to create anonymous strings of the required length. For this implementation I chose a basic algorithm, but I'm sure you can create one that is more sophisticated if you need it.

Th next thing we need to do is to implement the desired With method. That can be done with an extension method works on ObjectBuilder<T>:

public static class ObjectBuilderExtension
{
    public static ObjectBuilder<T> With<T>(
        this ObjectBuilder<T> ob,
        Expression<Func<T, string>> propertyPicker,
        int minimumLength,
        int maximumLength)
    {
        var me = (MemberExpression)propertyPicker.Body;
        var name = me.Member.Name;
        var generator =
            new ConstrainedStringGenerator(
                minimumLength, maximumLength);
        var value = generator.CreateaAnonymous(name);
        return ob.With(propertyPicker, value);
    }
}

The method takes the same input as ObjectBuilder<T>'s With method, plus the two integers that constrain the length. Note that the propertyPicker expression has been constrained to deal only with strings.

In this implementation, we use the ConstrainedStringGenerator class to generate the desired value for the property, where after we can use the existing With method to assign the value to the property in question.

This now allows us to write Build statements like the one originally requested:

var mc = fixture.Build<MyClass>()
    .With(x => x.SomeText, 0, 100)
    .CreateAnonymous();

The other part of the request, regarding NHibernate integration, I will leave to the interested reader – mostly because I have never used NHibernate, so I have no clue how to do it. I would, however, love to see a blog post with that addition.

This entire example is now part of the AutoFixture test suite, so if you are interested in looking at it in more detail, you can get it from the AutoFixture source code (available at CodePlex).

posted on Saturday, November 07, 2009 8:56:05 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, October 31, 2009

AutoFixture beta 1 is now available on the CodePlex site! We have been using AutoFixture quite intensively in Safewhere for almost half a year now, and the core of it has turned out to be stable and much more powerful than I originally imagined.

During that period, I have discovered and fixed a few bugs, but the most positive experience has been how extended usage has inspired us to come up with numerous ideas to new cool features. Some of these features are already implemented in the current release, and the rest are listed on the AutoFixture site.

The beta 1 release page has more details about this particular release.

posted on Saturday, October 31, 2009 9:59:43 AM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, October 26, 2009

A few months ago I described how you can use AutoFixture's With method to assign property values as part of building up an anonymous variable. In that scenario, the With method is used to explicitly assign a particular, pre-defined value to a property.

There's another overload of the With method that doesn't take an explicit value, but rather uses AutoFixture to create an anonymous value for the property. So what's the deal with that if AutoFixture's default behavior is to assign anonymous values to all writable properties?

In short it's an opt-in mechanism that only makes sense if you decide to opt out of the AutoProperties features.

As always, let's look at an example. This time, I've decided to show you a slightly more realistic example so that you can get an idea of how AutoFixture can be used to aid in unit testing. This also means that the example is going to be a little more complex than usual, but it's still simple.

Imagine that we wish to test that an ASP.NET MVC Controller Action returns the correct result. More specifically, we wish to test that the Profile method on MyController returns a ViewResult with the correct Model (the current user's name, to make things interesing).

Here's the entire test. It may look more complicated than it is – it's really only 10 lines of code, but I had to break them up to prevent unpleasant wrapping if your screen is narrow.

[TestMethod]
public void ProfileWillReturnResultWithCorrectUserName()
{
    // Fixture setup
    var fixture = new Fixture();
    fixture.Customize<ControllerContext>(ob => ob
        .OmitAutoProperties()
        .With(cc => cc.HttpContext));
 
    var expectedUserName = 
        fixture.CreateAnonymous("UserName");
 
    var httpCtxStub = new Mock<HttpContextBase>();
    httpCtxStub.SetupGet(x => x.User).Returns(
        new GenericPrincipal(
            new GenericIdentity(expectedUserName), null));
    fixture.Register(httpCtxStub.Object);
 
    var sut = fixture.Build<MyController>()
        .OmitAutoProperties()
        .With(c => c.ControllerContext)
        .CreateAnonymous();
    // Exercise system
    ViewResult result = sut.Profile();
    // Verify outcome
    var actual = result.ViewData.Model;
    Assert.AreEqual(expectedUserName, actual, "User");
    // Teardown
}

Apart from AutoFixture, I'm also making use of Moq to stub out HttpContextBase.

You can see the Anonymous With method in two different places: in the call to Customize and when the SUT is being built. In both cases you can see that the call to With follows a call to OmitAutoProperties. In other words: we are telling AutoFixture that we don't want any of the writable properties to be assigned a value except the one we identify.

Let me highlight some parts of the test.

fixture.Customize<ControllerContext>(ob => ob
    .OmitAutoProperties()
    .With(cc => cc.HttpContext));

This line of code instructs AutoFixture to always create a ControllerContext in a particular way: I don't want to use AutoProperties here, because ControllerContext has a lot of writable properties of abstract types, and that would require me to set up a lot of Test Doubles if I had to assign values to all of those. It's much easier to simply opt out of this mechanism. However, I would like to have the HttpContext property assigned, but I don't care about the value in this statement, so the With method simply states that AutoFixture should assign a value according to whatever rule it has for creating instances of HttpContextBase.

I can now set up a Stub that populates the User property of HttpContextBase:

var httpCtxStub = new Mock<HttpContextBase>();
httpCtxStub.SetupGet(x => x.User).Returns(
    new GenericPrincipal(
        new GenericIdentity(expectedUserName), null));
fixture.Register(httpCtxStub.Object);

This is registered with the fixture instance which closes the loop to the previous customization.

I can now create an instance of my SUT. Once more, I don't want to have to set up a lot of irrelevant properties on MyController, so I opt out of AutoProperties and then explicitly opt in on the ControllerContext. This will cause AutoFixture to automatically populate the ControllerContext with the HttpContext Stub:

var sut = fixture.Build<MyController>()
    .OmitAutoProperties()
    .With(c => c.ControllerContext)
    .CreateAnonymous();

For completeness' sake, here's the MyController class that I am testing:

public class MyController : Controller
{
    public ViewResult Profile()
    {
        object userName = this.User.Identity.Name;
        return this.View(userName);
    }
}

This test may seem complex, but it really accomplishes a lot in only 10 lines of code, considering that ASP.NET MVC Controllers with a working HttpContext are not particularly trivial to set up.

In summary, this With method overload lets you opt in on one or more explicitly identified properties when you have otherwise decided to omit AutoProperties. As all the other Builder methods, this method can also be chained.

posted on Monday, October 26, 2009 9:26:49 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, September 22, 2009

In the previous post on AutoFixture, I demonstrated how it's possible to use a customized Builder to perform complex initialization when requesting an instance of a particular type. To recap, this was the solution I described:

var mc = fixture.CreateAnonymous<MyClass>();
var mvm = fixture.Build<MyViewModel>()
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc)
    .CreateAnonymous();

This code first creates an anonymous instance of MyClass that can be added to MyViewModel. It then initializes a Builder for a specific instance of MyViewModel, instructing it to

  1. add the anonymous MyClass instance to the list of AvailableItems
  2. assign the same instance to the SelectedItem property

While this works splendidly, it can get tiresome to write the same customization over and over again if you need to create multiple instances of the same type. It also violate the DRY principle.

When this is the case, you can alternatively register a customized Builder pipeline for the type in question (in this case MyViewModel). This is done with the Customize method:

var mc = fixture.CreateAnonymous<MyClass>();
fixture.Customize<MyViewModel>(ob => ob
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc));

The Customize method takes as input a function that provides an initial ObjectBuilder as input, and returns a new, customized ObjectBuilder as output. This function is registered with the type, so that each time an anonymous instance of the type is requested, the customized ObjectBuilder will be used to create the instance.

In the example, I customize the supplied ObjectBuilder (ob) in exactly the same way as before, but instead of invoking CreateAnonymous, I simply return the customized ObjectBuilder to the Fixture instance. It then saves this customized ObjectBuilder for later use.

With this customization, what before failed now succeeds:

var mvm = fixture.CreateAnonymous<MyViewModel>();

The Customize method is the core method for customizing AutoFixture. Most other customization methods (like Register) are simply convenience methods that wraps Customize. It is a very powerful method that can be used to define some very specific Builder algorithms for particular types.

posted on Tuesday, September 22, 2009 4:53:48 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, September 21, 2009

Yesterday I released version .8.6 of AutoFixture. It is a minor release that simply adds some new features.

There are some minor breaking changes (documented on the release page), but they only affect supporting classes and don't touch on any of the code examples I have so far published. In other words, if you are using AutoFixture's fluent interface, your code should still compile.

Please go ahead and download it and use it. As always, comments and questions are welcome, either here or in the forum.

posted on Monday, September 21, 2009 7:37:36 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, September 02, 2009

It gives me great pleasure to announce that I have just release version .8.5 of AutoFixture. It is a minor release (hence the numbering) that mainly contains a lot of convenience overloads to already existing methods. There is also a single bug fix.

There are two breaking changes (documented on the release page), but they are minor and I do not expect them to cause problems. Only one of these even remotely affects any part of the API I have already discussed here, and that relates to what kind of exception is being thrown when AutoFixture is unable to create an instance of the requested type.

Please go ahead and download it and use it heavily :) As always, comments and questions are welcome.

posted on Wednesday, September 02, 2009 10:21:13 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, August 25, 2009

Soon after I posted my post on the AutoFixture Custom Builder's Do method, a much better example occurred to me, so let's revisit this feature in light of a more reasonable context.

When I write WPF code, I always use the MVVM pattern. When I need to create a Master/Detail View, I usually model it so that my View Model has a list of available items, and a property that returns the currently selected item. In this way, I can bind the current Detail View to the currently selected item purely through the View Model.

Such a View Model might look like this:

public class MyViewModel
{
    private readonly List<MyClass> availableItems;
    private MyClass selectedItem;
 
    public MyViewModel()
    {
        this.availableItems = new List<MyClass>();
    }
 
    public ICollection<MyClass> AvailableItems
    {
        get { return this.availableItems; }
    }
 
    public MyClass SelectedItem
    {
        get { return this.selectedItem; }
        set 
        {
            if (!this.availableItems.Contains(value))
            {
                throw new ArgumentException("...");
            }
            this.selectedItem = value;
        }
    }
}

The main point of interest is that if you attempt to set SelectedItem to an instance that's not contained in the list of available items, an exception will be thrown. That's reasonable behavior, since we want the user to select only from the available items.

By default, AutoFixture works by assigning an Anonymous Value to all writable properties. Since these values are auto-generated, the value AutoFixture is going to assign to SelectedItem will be a new instance of MyClass, and thus not one of the available items. In other words, this will throw an exception:

var mvm = fixture.CreateAnonymous<MyViewModel>();

There are several solutions to this situation, depending on the scenario. If you need an instance with SelectedItem correctly set to a non-null value, you can use the Do method like this:

var mc = fixture.CreateAnonymous<MyClass>();
var mvm = fixture.Build<MyViewModel>()
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc)
    .CreateAnonymous();

This first creates an anonymous instance of MyClass, adds it to AvailableItems as part of a customized Builder pipeline and subsequently assigns it to SelectedItem.

Another option is to skip assigning only the SelectedItem property. This is a good option if you don't need that value in a particular test. You can use the Without method to do that:

var mvm = fixture.Build<MyViewModel>()
    .Without(s => s.SelectedItem)
    .CreateAnonymous();

This will assign a value to all other writable properties of MyViewModel (if it had had any), except the SelectedItem property. In this case, the value of SelectedItem will be null, since it is being ignored.

Finally you can simply choose to omit all AutoProperties using the OmitAutoProperties method:

var mvm = fixture.Build<MyViewModel>()
    .OmitAutoProperties()
    .CreateAnonymous();

In this scenario, only MyViewModel's constructor is being executed, while all writable properties are being ignored.

As you can see, AutoFixture offers great flexibility in providing specialized custom Builders that fit almost any situation.

posted on Tuesday, August 25, 2009 8:27:39 PM (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Monday, August 17, 2009

The default behavior of AutoFixture is to create an Anonymous Variable by assigning a value to all writable properties of the created instance. This is great in many scenarios, but not so much in others. You can disable this behavior by using the OmitAutoProperties method, but sometimes, you would like most of the writable properties set, except one or two.

Consider this simple Person class:

public class Person
{
    private Person spouse;
 
    public DateTime BirthDay { get; set; }
 
    public string Name { get; set; }
 
    public Person Spouse 
    {
        get { return this.spouse; }
        set
        {
            this.spouse = value;
            if (value != null)
            {
                value.spouse = this;
            }
        }
    }
}

The main trouble with this class, seen from AutoFixture's perspective, is the circular reference exposed by the Spouse property. When AutoFixture attempts to create an anonymous instance of Person, it will create anonymous values for all writable properties, and that includes the Spouse property, so it attempts to create a new instance of the Person class and assign values to all public properties, including the Spouse property, etc.

In other words, this line of code throws a StackOverflowException:

var person = fixture.CreateAnonymous<Person>();

If you would still like to have anonymous values assigned to Name and BirthDay, you can use the Without method:

var person = fixture.Build<Person>()
    .Without(p => p.Spouse)
    .CreateAnonymous();

This will give you an anonymous instance of the Person class, but with the Spouse property still with its default value of null.

Several calls to Without can be chained if you want to skip more than one property.

posted on Monday, August 17, 2009 9:33:40 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, July 23, 2009

Since AutoFixture is a Test Data Builder, one of its most important tasks is to build up graphs of fully populated, yet semantically correct, strongly typed objects. As such, its default behavior is to assign a value to every writable property in the object graph.

While this is sometimes the desired behavior, at other times it is not.

This is particularly the case when you want to test that a newly created object has a property of a particular value. When you want to test the default value of a writable property, AutoFixture's AutoProperty feature is very much in the way.

Let's consider as an example a piece of software that deals with vehicle registration. By default, a vehicle should have four wheels, since this is the most common occurrence. Although I always practice TDD, I'll start by showing you the Vehicle class to illustrate what I mean.

public class Vehicle
{
    public Vehicle()
    {
        this.Wheels = 4;
    }
 
    public int Wheels { get; set; }
}

Here's a test that ensures that the default number of wheels is 4 – or does it?

In fact the assertion fails because the actual value is 1, not 4.

[TestMethod]
public void AnonymousVehicleHasWheelsAssignedByFixture()
{
    // Fixture setup
    var fixture = new Fixture();
    var sut = fixture.CreateAnonymous<Vehicle>();
    // Exercise system
    var result = sut.Wheels;
    // Verify outcome
    Assert.AreEqual<int>(4, result, "Wheels");
    // Teardown
}

Why does the test fail when the value of Wheels is set to 4 in the constructor? It fails because AutoFixture is designed to create populated test data, so it assigns a value to every writable property. Wheels is a writable property, so AutoFixture assigns an integer value to it using its default algorithm for creating anonymous numbers. Since no other numbers are being created during this test, the number assigned to Wheels is 1. This is AutoFixture's AutoProperties feature in effect.

When you want to test constructor logic, or otherwise wish to disable the AutoProperties feature, you can use a customized Builder with the OmitAutoProperties method:

[TestMethod]
public void VehicleWithoutAutoPropertiesWillHaveFourWheels()
{
    // Fixture setup
    var fixture = new Fixture();
    var sut = fixture.Build<Vehicle>()
        .OmitAutoProperties()
        .CreateAnonymous();
    // Exercise system
    var result = sut.Wheels;
    // Verify outcome
    Assert.AreEqual<int>(4, result, "Wheels");
    // Teardown
}

The OmitAutoProperties method instructs AutoFixture to skip assigning automatic Anonymous Values to all writable properties in the object graph. Any properties specifically assigned by the With method will still be assigned.

The test using OmitAutoProperties succeeds.

posted on Thursday, July 23, 2009 4:54:45 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Saturday, July 11, 2009

A couple of days ago I released AutoFixture .8.4. It contains a few small feature additions and a bug fix. You can get it at the AutoFixture CodePlex site as usual.

You may have noticed that I'm frequently releasing incremental versions these days. This is because we have begun using AutoFixture for writing production software at Safewhere. So far, it has been a pleasure to use AutoFixture in my daily work, and watch colleagues pick it up and run with it.

Such intensive usage obviously uncovers missing features as well as a few bugs, which is the driving force behind the frequent releases. I've been happy to observe that so far, there have been only a few bugs, and the general API is very expressive and useful.

After we ship the first product written with AutoFixture, I plan to upgrade it to version .9 (beta). That should hopefully happen in the autumn of 2009.

posted on Saturday, July 11, 2009 10:35:34 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Wednesday, July 01, 2009

Some time ago, my good friend Martin Gildenpfennig from Ative made me aware that AutoFixture (among other things) is an generic implementation of the Test Data Builder pattern, and indeed it is.

In the original Gang of Four definition of a Design Pattern, several people must independently have arrived at the same general solution to a given problem before we can call a coding idiom a true Pattern. In this spirit, the Test Data Builder pattern is on the verge of becoming a true Design Pattern, since I came up with AutoFixture without having heard about Test Data Builder :)

The problem is the same: How do we create semantically correct test objects in a manner that is flexible and yet hides away irrelevant complexity?

Like others before me, I tried the Object Mother (anti?)pattern and found it lacking. To me the answer was AutoFixture, a library that heuristically builds object graphs using Reflection and built-in rules for specific types.

Although my original approach was different, you can certainly use AutoFixture as a generic Test Data Builder.

To demonstrate this, let's work with this (oversimplified) Order object model:

image

Assuming that we have an instance of the Fixture class (called fixture), we can create a new instance of the Order class with a ShippingAddress in Denmark:

var order = fixture.Build<Order>()
    .With(o => o.ShippingAddress, 
        fixture.Build<Address>()
        .With(a => a.Country, "Denmark")
        .CreateAnonymous())
    .CreateAnonymous();

While this works and follows the Test Data Builder pattern, I find this more concise and readable:

var order = fixture.CreateAnonymous<Order>();
order.ShippingAddress.Country = "Denmark";

The result is the same.

We can also add anonymous order lines to the order using this fluent interface:

var order = fixture.Build<Order>()
    .Do(o => fixture.AddManyTo(o.OrderLines))
    .CreateAnonymous();

but again, I find it easier to simply let AutoFixture create a fully anonymous Order instance, and then afterwards modify the relevant parts:

var order = fixture.CreateAnonymous<Order>();
fixture.AddManyTo(order.OrderLines);

Whether you prefer one style over the other, AutoFixture supports them both.

posted on Wednesday, July 01, 2009 8:19:00 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Saturday, June 20, 2009

It was only earlier this week that I released AutoFixture .8.2, but now I'm releasing version .8.3 – not that there was anything wrong with .8.2 (that I know of), but I had some time to implement new features, and I wanted to properly release those.

In the future I will blog about these new features (along with all the other AutoFixture features I haven't introduced yet).

Get it at the AutoFixture CodePlex site as usual.

posted on Saturday, June 20, 2009 10:34:30 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, June 18, 2009

Yesterday I created a new release (.8.2) of AutoFixture; this time with a new feature that I recently discovered that I needed, and about which I will blog later.

There are no breaking changes and no known bugs.

posted on Thursday, June 18, 2009 9:11:39 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, June 09, 2009

Previously, we saw how you can set property values while building anonymous variables with AutoFixture. While I insinuated that I consider this a somewhat atypical scenario, we can now safely venture forth to the truly exotic :)

Imagine that you want to build an anonymous instance of a type that requires you to call a certain method before you can start assigning properties. It's difficult to come up with a reasonable example of this, but although I consider it quite bad design, I've seen interfaces that include an Initialize method that must be called before any other member. In our example, let's call this interface IBadDesign.

Let's say that we have a class called SomeImp that implements IBadDesign. Here's the relevant part of the class:

#region IBadDesign Members
 
public string Message
{
    get { return this.message; }
    set
    {
        if (this.mc == null)
        {
            throw new InvalidOperationException("...");
        }
 
        this.message = value;
        this.transformedMessage = this.mc.DoStuff(value);
    }
}
 
public void Initialize(MyClass mc)
{
    this.mc = mc;
}
 
#endregion

This is a rather ridiculous example, but I couldn't think of a better one. The main point here is that given a brand-new instance of SomeImp, this usage is invalid:

something.Message = "Ploeh";

While the above code snippet will throw an InvalidOperationException, this will work:

something.Initialize(new MyClass());
something.Message = "Ploeh";

The problem is that by default, AutoFixture ignores methods and only assigns properties, which means that this is also going to throw:

var imp = fixture.CreateAnonymous<SomeImp>();

As we saw with properties, we can use the Build method to customize how the type is being created. Properties can be set with the With method, while methods can be invoked with the Do method, so this is all it takes:

var imp = fixture.Build<SomeImp>()
    .Do(s => s.Initialize(new MyClass()))
    .CreateAnonymous();    

We don't have to explicitly set the Message property, as AutoFixture is going to do this automatically, and all implicit assignments happen after explicit actions defined by With or Do (and in case you were wondering, you can mix With and Do, and ObjectBuilder<T> will preserve the ordering).

In most cases, having to use the Do method probably constitutes a design smell of the SUT, but the method is there if you need it.

posted on Tuesday, June 09, 2009 7:50:54 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, June 04, 2009

To make it a bit easier to get started with AutoFixture without having to trawl through all my blog posts, I've added a Cheat Sheet over at the AutoFixture CodePlex site.

As I add more posts on AutoFixture, I'll update the Cheat Sheet with the essentials. Please let me know if you think something's missing.

posted on Thursday, June 04, 2009 11:15:08 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, June 01, 2009

In my previous post I described how the Build method can be used to customize how a single anonymous variable is created.

A common customization is to set a property value during creation. In most cases, this can simply be done after the anonymous variable has been created (so the following is not an AutoFixture customization):

var mc = fixture.CreateAnonymous<MyClass>();
mc.MyText = "Ploeh";

By default, AutoFixture assigns anonymous values to all writable properties, but since they are writable, you can always explicitly give them different values if you care.

However, there are situations when a property is writable, but can't take just any value of its type. Sometimes this is a sign that you should reconsider your API, as I've previously described, but it may also be a legitimate situation.

Consider a Filter class that has Min and Max properties. To be semantically correct, the Min property must be less than or equal to the Max property. Each property is implemented like this:

public int Min
{
    get { return this.min; }
    set
    {
        if (value > this.Max)
        {
            throw new ArgumentOutOfRangeException("value");
        }
        this.min = value;
    }
}

When you ask AutoFixture to create an instance of the Filter class, it will throw an exception because it's attempting to set the Min property after the Max property, and the default algorithm for numbers is to return numbers in an increasing sequence. (In this example, the Min property is being assigned a value after the Max property, but AutoFixture has no contract that states that the order in which properties are assigned is guaranteed.) In other words, this throws an exception:

var f = fixture.CreateAnonymous<Filter>();

To solve this problem, we will have to customize the assignment of the Min and Max properties, before we ask AutoFixture to create an instance of the Filter class. Here's how to do that:

int min = fixture.CreateAnonymous<int>();
int max = min + 1;
var f = fixture.Build<Filter>()
    .With(s => s.Max, max)
    .With(s => s.Min, min)
    .CreateAnonymous();

The With method lets you specify an expression that identifies a property, as well as the value that should be assigned to that property. When you do that, AutoFixture will never attempt to assign an anonymous value to that property, but will instead use the value you specified.

In most cases, just creating a truly anonymous instance and subsequently explicitly assigning any significant values is easier, but using the Build method with one or more calls to the With method gives you the power to override any property assignments before the instance is created.

posted on Monday, June 01, 2009 2:35:18 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, May 26, 2009

Until now, I've shown you how you can make wholesale adjustments or customizations to an entire Fixture instance, effectively changing the way it creates all instances of a particular type.

In some scenarios, you'd rather want to customize how a single instance is created without influencing other instances of the same type. For this purpose, AutoFixture includes a class called ObjectBuilder<T> that can be used to do exactly that.

The easiest way to get an instance of this class is by calling Build on a Fixture instance. This will give you an instance of ObjectBuilder<T> that you can use to customize the build steps. When you are done, CreateAnonymous returns the built instance.

var mc = fixture.Build<MyClass>().CreateAnonymous();

This particular example doesn't define any customizations, so it's equivalent to

var mc = fixture.CreateAnonymous<MyClass>();

In fact, Fixture.CreateAnonymous is little more than a convenience method wrapping an ObjectBuilder (there's a few extra differences, but that's a topic for another post).

It's worth noting that the object specified by the type parameter to the Build method is first created when you call CreateAnonymous.

In future posts I'll demonstrate how to use the Build method to customize individual anonymous variables.

posted on Tuesday, May 26, 2009 11:30:35 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Sunday, May 17, 2009

Today I've created a new release (.8.1 for lack of a better version number) of AutoFixture. While it contains some breaking changes, they all relate to features that I have yet to cover here on the blog – in other words: All the examples that I've posted so far are still valid.

posted on Sunday, May 17, 2009 9:48:36 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Friday, May 15, 2009

Dear reader, I hope you are still with me!

After eight posts of AutoFixture feature walkthroughs, I can't blame you for wondering why this tool might even be relevant to you. In this post, we'll finally begin to look at how AutoFixture can help you towards Zero-Friction TDD!

In an earlier post, I described how the Fixture Object pattern can help you greatly reduce the amount of test code that you have to write. Since AutoFixture was designed to act as a general-purpose Fixture Object, it can help you reduce the amount of test code even further, letting you focus on specifying the behavior of your SUT.

In that former post, the original example was this complex test that I will repeat in it's entirety for your benefit (or horror):

[TestMethod]
public void NumberSumIsCorrect_Naïve()
{
    // Fixture setup
    Thing thing1 = new Thing()
    {
        Number = 3,
        Text = "Anonymous text 1"
    };
    Thing thing2 = new Thing()
    {
        Number = 6,
        Text = "Anonymous text 2"
    };
    Thing thing3 = new Thing()
    {
        Number = 1,
        Text = "Anonymous text 3"
    };
 
    int expectedSum = new[] { thing1, thing2, thing3 }.
        Select(t => t.Number).Sum();
 
    IMyInterface fake = new FakeMyInterface();
    fake.AddThing(thing1);
    fake.AddThing(thing2);
    fake.AddThing(thing3);
 
    MyClass sut = new MyClass(fake);
    // Exercise system
    int result = sut.CalculateSumOfThings();
    // Verify outcome
    Assert.AreEqual<int>(expectedSum, result,
        "Sum of things");
    // Teardown
}

This test consists of 18 lines of code.

Using the Fixture Object pattern, I was able to cut that down to 7 lines of code, which is a 61% improvement (however, the downside was an additional 19 lines of (reusable) code for MyClassFixture, so the benefit can only be reaped when you have multiple tests leveraged by the same Fixture Object. This was all covered in the former post, to which I will refer you).

With AutoFixture, we can do much better. Here's a one-off rewrite of the unit test using AutoFixture:

[TestMethod]
public void NumberSumIsCorrect_AutoFixture()
{
    // Fixture setup
    Fixture fixture = new Fixture();
    IMyInterface fake = new FakeMyInterface();
    fixture.Register<IMyInterface>(() => fake);
 
    var things = fixture.CreateMany<Thing>().ToList();
    things.ForEach(t => fake.AddThing(t));
    int expectedSum = things.Select(t => t.Number).Sum();
 
    MyClass sut = fixture.CreateAnonymous<MyClass>();
    // Exercise system
    int result = sut.CalculateSumOfThings();
    // Verify outcome
    Assert.AreEqual<int>(expectedSum, result,
        "Sum of things");
    // Teardown
}

In this test, I map the concrete fake instance to the IMyInterface type in the fixture object, and then use its ability to create many anonymous instances with one method call. Before exercising the SUT, I also use the fixture instance as a SUT Factory.

Apart from AutoFixture (and FakeMyInterface, which is invariant for all variations, and thus kept out of the comparison), this test stands alone, but still manages to reduce the number of code lines to 10 lines – a 44% improvement! In my book, that's already a significant gain in productivity and maintainability, but we can do better!

If we need to test MyClass repeatedly in similar ways, we can move the common code to a Fixture Object based on AutoFixture, and the test can be refactored to this:

[TestMethod]
public void NumberSumIsCorrect_DerivedFixture()
{
    // Fixture setup
    MyClassFixture fixture = new MyClassFixture();
    fixture.AddManyTo(fixture.Things);
 
    int expectedSum = 
        fixture.Things.Select(t => t.Number).Sum();
    MyClass sut = fixture.CreateAnonymous<MyClass>();
    // Exercise system
    int result = sut.CalculateSumOfThings();
    // Verify outcome
    Assert.AreEqual<int>(expectedSum, result,
        "Sum of things");
    // Teardown
}

Now we are back at 7 lines of code, which is on par with the original Fixture Object-based test, but now MyClassFixture is reduced to 8 lines of code:

internal class MyClassFixture : Fixture
{
    internal MyClassFixture()
    {
        this.Things = new List<Thing>();
        this.Register<IMyInterface>(() =>
            {
                var fake = new FakeMyInterface();
                this.Things.ToList().ForEach(t =>
                    fake.AddThing(t));
                return fake;
            });
    }
 
    internal IList<Thing> Things { get; private set; }
}

Notice how I've moved the IMyInterface-to-FakeMyInterface mapping to MyClassFixture. Whenever it's asked to create a new instance of IMyInterface, MyClassFixture makes sure to add all the Thing instances to the fake before returning it.

Compared to the former Fixture Object of 19 lines, that's another 58% improvement. Considering some of the APIs I encounter in my daily work, the above example is even rather simple. The more complex and demanding your SUT's API is, the greater the gain from using AutoFixture will be, since it's going to figure out much of the routine stuff for you.

With this post, I hope I have given you a taste of the power that AutoFixture provides. It allows you to focus on specifying the behavior of your SUT, while taking care of all the infrastructure tedium that tends to get in the way.

posted on Friday, May 15, 2009 7:34:00 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, May 11, 2009

When writing unit tests you often need to deal with sequences and collections, populating lists with anonymous data as part of setting up a Fixture.

This is easy to do with AutoFixture. While you can obviously create a simple loop and call CreateAnonymous from within the loop, AutoFixture provides some convenient methods for working with sequences.

Equivalent to the CreateAnonymous method, the Fixture class also includes the CreateMany method that creates a sequence of anonymous variables. CreateManyAnonymous might have been a more concise and consistent name for the method, but I felt that this was a bit too verbose.

This will create an IEnumerable<string>:

Fixture fixture = new Fixture();
var strings = fixture.CreateMany<string>();

Obvously, you can create sequences of whatever type you want, as long as AutoFixture can figure out how to create instances of the type:

var myInstances = fixture.CreateMany<MyClass>();

Being able to create sequences of anonymous data is nice, but sometimes you need to add multiple anonymous items to an existing list (particularly if that list is a read-only property of your SUT).

To support that scenario, the Fixture class also has the AddManyTo method that can be used like this:

var list = new List<MyClass>();
fixture.AddManyTo(list);

This simply creates many anonymous MyClass instances and adds them all to the list. Once more, AddManyAnonymousTo might have been a more precise name, but again I chose a less verbose alternative.

If you want more control over how the instances are created, a more explicit overload of AddManyTo gives you that.

var list = new List<int>();
var r = new Random();
fixture.AddManyTo(list, () => r.Next());

The above examples adds many random numbers to the list of integers, since the second parameters is a Func<T> used to create the instances.

By default, these methods all create 3 anonymous variables when called, since 3 is a good equivalent for many. If you want a different number of instances to be created, you can modify the RepeatCount property.

fixture.RepeatCount = 10;
var sequence = fixture.CreateMany<MyClass>();

The above example will create an IEnumerable<MyClass> with 10 anonymous MyClass instances, while this will add 7 anonymous instances to the list variable:

var list = new List<MyClass>();
fixture.RepeatCount = 7;
fixture.AddManyTo(list);

AutoFixture provides some convenient methods for creating and managing collections of anonymous data. While it may seem simple (and it is), in a future post I will demonstrate how it can save you quit a bit of infrastructure code, and enable you to write unit tests that are shorter, more concise and more maintainable.

posted on Monday, May 11, 2009 10:25:42 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Friday, May 01, 2009

As a response to my description of how AutoFixture creates objects, Klaus asked:

“[What] if the constructor of ComplexChild imposes some kind of restriction on its parameter? If, for example, instead of the "name" parameter, it would take a "phoneNumber" parameter (as a string), and do some format checking?”

Now that we have covered some of the basic features of AutoFixture, it’s time to properly answer this excellent question.

For simplicity’s sake, let’s assume that the phone number in question is a Danish phone number: This is pretty good for example code, since a Danish phone number is essentially just an 8-digit number. It can have white space and an optional country code (+45), but strip that away, and it’s just an 8-digit number. However, there are exceptions, since the emergency number is 112 (equivalent to the American 911), and other 3-digit special numbers exist as well.

With that in mind, let’s look at a simple Contact class that contains a contact’s name and Danish phone number. The constructor might look like this:

public Contact(string name, string phoneNumber)
{
    this.Name = name;
    this.PhoneNumber = 
        Contact.ParsePhoneNumber(phoneNumber);
}

The static ParsePhoneNumber method strips away white space and optional country code and parses the normalized string to a number. This fits the scenario laid out in Klaus’ question.

So what happens when we ask AutoFixture to create an instance of Contact? It will Reflect over Contact’s constructor and create two new anonymous string instances – one for name, and one for phoneNumber. As previously described, each string will be created as a Guid prepended with a named hint – in this case the argument name. Thus, the phoneNumber argument will get a value like "phoneNumberfa432351-1563-4769-842c-7588af32a056", which will cause the ParsePhoneNumber method to throw an exception.

How do we deal with that?

The most obvious fix is to modify AutoFixture’s algorithm for generating strings. Here an initial attempt:

fixture.Register<string>(() => "112");

This will simply cause all generated strings to be "112", including the Contact instance's Name property. In unit testing, this may not be a problem in itself, since, from an API perspective, the name could in principle be any string.

However, if the Contact class also had an Email property that was parsed and verified from a string argument, we'd be in trouble, since "112" is not a valid email address.

We can't easily modify the string generation algorithm to fit the requirements for both a Danish telephone number and an email address.

Should we then conclude that AutoFixture isn't really useful after all?

On the contrary, this is a hint to us that the Contact class' API could be better. If an automated tool can't figure out how to generate correct input, how can we expect other developers to do it?

Although humans can make leaps of intuition, an API should still go to great lengths to protect its users from making mistakes. Asking for an unbounded string and then expecting it to be in a particular format may not always be the best option available.

In our particular case, the Value Object pattern offers a better alternative. Our first version of the DanishPhoneNumber class simply takes an integer as a constructor argument:

public DanishPhoneNumber(int number)
{
    this.number = number;
}

If we still need to parse strings (e.g. from user input), we could add a static Parse, or even a TryParse, method and test that method in isolation without involving the Contact class.

This neatly solves our original issue with AutoFixture, since it will now create a new instance of DanishPhoneNumber as part of the creation process when we ask for an anonymous Contact instance.

The only remaining issue is that by default, the number fed into the DanishPhoneNumber instance is likely to be considerably less than 112 – actually, if no other Int32 instances are created, it will be 1.

This will be a problem if we modify the DanishPhoneNumber constructor to look like this:

public DanishPhoneNumber(int number)
{
    if ((number < 112) ||
        (number > 99999999))
    {
        throw new ArgumentOutOfRangeException("number");
    }
    this.number = number;
}

Unless a unit test has already caused AutFixture to previously create 111 other integers (highly unlikely), CreateAnonymous<Contact> is going to throw an exception.

This is easy to fix. Once again, the most obvious fix is to modify the creation algorithm for integers.

fixture.Register<int>(() => 12345678);

However, this will cause that particular instance of Fixture to return 12345678 every time you ask it to create an anonymous integer. Depending on the scenario, this may or may not be a problem.

A more targeted solution is to specifically address the algorithm for generating DanishPhoneNumber instances:

fixture.Register<int, DanishPhoneNumber>(i => 
    new DanishPhoneNumber(i + 112));

Here, I've even used the Register overload that automatically provides an anonymous integer to feed into the DanishPhoneNumber constructor, so all I have to do is ensure that the number falls into the proper range. Adding 112 (the minimum) neatly does the trick.

If you don't like the hard-coded value of 112 in the test, you can use that to further drive the design. In this case, we can add a MinValue to DanishPhoneNumber:

fixture.Register<int, DanishPhoneNumber>(i =>
    new DanishPhoneNumber(i + 
        DanishPhoneNumber.MinValue));

Obvously, MinValue will also be used in DanishPhoneNumber's constructor to define the lower limit of the Guard Clause.

In my opinion, a good API should guide the user and make it difficult to make mistakes. In many ways, you can view AutoFixture as an exceptionally dim user of your API. This is the reason I really enjoyed receiving Klaus' original question: Like other TDD practices, AutoFixture drives better design.

posted on Friday, May 01, 2009 5:56:00 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, April 27, 2009

Several times in my previous AutoFixture posts, I’ve insinuated that you can change the algorithms used for creating strings, numbers and so on, if you don’t like the defaults.

One way you can do this is by simply using the Register method that I introduced in my previous post. Let’s say that you want to replace the string algorithm to simply return a specific string:

fixture.Register<string>(() => "ploeh");

No matter how many times you’ll call CreateAnonymous<string> on that particular fixture object, it will always return ploeh.

The Register method is really only a type-safe convenience method that wraps access to the TypeMappings property. TypeMappings is just a Dictionary of types mapped to functions. By default, the Fixture class has a set of pre-defined TypeMappings for primitive types such as strings, numbers and booleans, so you could access the function used to generate strings by indexing into this Dictionary with the System.String type.

Equivalent to the above example, you could alternatively replace the string algorithm like this:

fixture.TypeMappings[typeof(string)] = s => "fnaah";

Instead of using the Register method, I here assign a lambda expression directly to the key identified by the System.String type. This is what the Register method does, so the result is exactly the same.

However, you may have noticed that by accessing TypeMappings directly, the signature of the function is different. The Register method takes a Func<T>, whereas the TypeMappings Dictionary expects a Func<object, object>. As you can see, the Register method is more type-safe, but the TypeMappings Dictionary gives you a chance to utilize the optional seed that one of the CreateAnonymous overloads takes.

You could, for example, do this:

fixture.TypeMappings[typeof(string)] = s =>
    string.Format((string)s, new Random().Next(100));

Although this particular algorithm has a built-in weakness (can you spot it?), we can now use the seed to provide a format string, like this:

string result = fixture.CreateAnonymous("Risk: {0}%");

which will yield a result like Risk: 32%.

When I designed the extensibility mechanism for AutoFixture, I seriously considered defining an interface that all TypeMappings had to implement, but I ended up preferring a Func<object, object> instead, since this allows you to redefine a particular algorithm inline in a test by using an anonymous delegate or lambda expression, and you can also reuse an existing algorithm, as long as it fits the signature.

posted on Monday, April 27, 2009 7:42:07 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, April 23, 2009

Now that I’ve described how AutoFixture creates objects, it’s time to look at a bit more advanced scenario. As you may recall, AutoFixture creates an object graph based on the public constructors of the types contained in that object graph.

That’s all well and good when all involved types have public constructors, but what happens when this is not the case?

Imagine that the MyClass constructor has this signature:

public MyClass(IMyInterface mi)

Since IMyInterface is an interface it has no public constructors, so this will not work:

Fixture fixture = new Fixture();
MyClass sut = fixture.CreateAnonymous<MyClass>();

The second line of code will throw an ArgumentException ObjectCreationException* stating that “AutoFixture was unable to create an instance of type Ploeh.QualityTools.AutoFixtureDocumentationTest.Intermediate.IMyInterface, since it has no public constructor.” Not terribly surprising, actually.

To resolve this issue, the Register method allows you to specify a custom function that creates an object of the requested type. In the case of IMyInterface, that would be a Func<IMyInterface>:

Fixture fixture = new Fixture();
fixture.Register<IMyInterface>(() => 
    new FakeMyInterface());
MyClass sut = fixture.CreateAnonymous<MyClass>();

Here, I use a lambda expression to register the FakeMyInterface type, so that every time that particular Fixture instance is asked to create an instance of IMyInterface, it will invoke the lambda expression, and thus return an instance of FakeMyInterface (which obviously implements IMyInterface).

The Register method simply lets you map types without public constructors to concrete types created by a function you specify.

A more advanced scenario arises if you wish to use a specific text with this FakeMyInterface constructor overload:

public FakeMyInterface(int number, string text)

Obviously, you can do it manually like this:

Fixture fixture = new Fixture();
int anonymousNumber = fixture.CreateAnonymous<int>();
string knownText = "This text is not anonymous";
fixture.Register<IMyInterface>(() => 
    new FakeMyInterface(anonymousNumber, knownText));

Here, I simply use the fixture object to create an anonymous number, while the knownText variable is explicitly assigned a value, and then both are used as outer variables in the Register function.

This is, however, a common scenario, so the Register method has some convenience overloads that will supply anonymous input parameters for you to use or throw away as you like. This means that I can rewrite the above example to this:

Fixture fixture = new Fixture();
string knownText = "This text is not anonymous";
fixture.Register<int, string, IMyInterface>((i, s) => 
    new FakeMyInterface(i, knownText));

Compared to the previous example, I save a line of code. The drawback is that I have to explicitly specify the type parameters to the Register method. In my book, that’s a pretty good tradeoff, as it removes a line of irrelevant code, and allows the test to focus on the relevant parts.

Notice that this Register overload creates both an anonymous integer and an anonymous string, but since I don’t want to use the anonymous string (s), I just ignore it and use the knownText variable instead.

*Edit (2009-09-02): Changed the name of the Exception type to correctly reflect a breaking change introduced in AutoFixture .8.5.

posted on Thursday, April 23, 2009 9:51:42 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Sunday, April 19, 2009

(Just back after 14 days in Morocco, I'll pick up where I left…)

The last group of built-in special creation algorithms for AutoFixture, besides strings and numbers, concerns Booleans.

The default algorithm is to alternate between true and false, starting with true; i.e. the first time you invoke

fixture.CreateAnonymous<bool>();

it will return true, the next time false, then true again, etc.

The reason I chose this algorithm was because I wanted to ensure that the first time AutoFixture creates an anonymous Boolean, it will return true, which is different than the default (false, in case you were in doubt). This gives us better assurance that a given constructor argument or property is being assigned a real value instead of the default.

Like with numbers, using the overload that takes a seed has no effect, and the seed is simply ignored.

fixture.CreateAnonymous(true);

In other words, the above method is still going to return false every second time, so it doesn’t really make sense to use this overload at all for Booleans (or numbers).

posted on Sunday, April 19, 2009 7:40:36 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Friday, April 03, 2009

Previously, we saw how AutoFixture creates strings. In this post, I’ll explain how it creates numbers. Once again, the algorithm that I’ll explain here is the default algorithm, but if you don’t like it, you can replace it with something else.

It’s very simple: Numbers are returned in the ordered sequence of natural numbers (1, 2, 3, 4, 5, …). The first time you call

fixture.CreateAnonymous<int>();

the returned number will be 1, the second time 2, etc.

The reason I chose that particular algorithm is because it creates numbers that we, as humans, find… well… natural!

A lot of the domains we model work with natural numbers, and even if you write an API where negative numbers are allowed, it’s fairly unlikely that positive numbers will not be allowed. Thus, in most cases, small positive integers tend to be ‘nice’ values in most APIs – and recall that when we do TDD, we focus on the Happy Path, so it’s important to pick values that take us down that path.

Using the overload that takes a seed, like this:

fixture.CreateAnonymous(42);

has no effect – the seed (in this case 42) is simply ignored, so if you call this after first calling the parameterless overload twice, the return number is going to be 3.

Each number type, however, has its own sequence, so even if you’ve been creating a few Int32 instances like above,

fixture.CreateAnonymous<decimal>();

will return 1.

The following number types all work that way:

  • Byte
  • Decimal
  • Double
  • Int16
  • Int32
  • Int64
  • SByte
  • Single
  • UInt16
  • UInt32
  • UInt64
posted on Friday, April 03, 2009 11:07:13 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, April 02, 2009

As previously hinted, AutoFixture creates primitive types like strings, numbers, etc. using special algorithms.

In this post, I’ll describe the default algorithm for strings. If you don’t like this particular algorithm, you can replace it with your own.

If you don’t care about the created string at all, you can just create it like this:

string anonymousText = 
    fixture.CreateAnonymous<string>();

The algorithm is simply to create a new Guid and convert it to a string, so that anonymousText will have a value like “f5cdf6b1-a473-410f-95f3-f427f7abb0c7”. Obviously, you don’t know exactly which value will be returned, but that’s the whole point of Constrained Non-Determinism.

When I create string values as Explicit Expectations, I prefer that the Assert failure message contains some sort of hint for me, so I can instead provide a hint to the CreateAnonymous method:

string anonymousName = fixture.CreateAnonymous("Name");

This overload is still generic, but since I provide a string as input, type inferencing takes care of the rest.

This is still going to create a Guid, but will now prepend the hint, giving a string like “Name30a35da1-d681-441b-9db3-77ff51728b58”.

Now, when my test fails, I’ll get an error message equivalent to

“Assert.AreEqual failed. Expected:<Namef2b1f55b-e9dc-4aac-a1ab-128dc80d3b71>. Actual:<ploeh>. Boo hiss”

which I find marginally more informative than if the hint hadn’t been there.

In a future post, I’ll explain how you can replace this algorithm with something else.

posted on Thursday, April 02, 2009 7:29:35 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, March 24, 2009

AutoFixture creates Anonymous Variables, but you’d probably like to know how it does it. This post explains how.

As we previously saw, the CreateAnonymous method can create a new instance of a type known to it only from its type parameter:

MyClass sut = fixture.CreateAnonymous<MyClass>();

AutoFixture was never compiled with any knowledge of the MyClass type, so it obviously uses Reflection to create the instance. That’s hardly surprising in itself.

In the case of MyClass, it has a default constructor, so creating an instance is as simple as it can be, but what happens if we instead ask for a more complex instance?

As an example, the ComplexParent type has this constructor:

public ComplexParent(ComplexChild child)

ComplexChild, however, has two constructors:

public ComplexChild(string name)

and

public ComplexChild(string name, int number)

So what happens when we ask AutoFixture to create an instance of ComplexParent?

ComplexParent only has a single public constructor, so AutoFixture doesn’t have any other choice than picking that. This means that it must now create an anonymous instance of ComplexChild.

Fortunately, AutoFixture’s raison d’être is creating objects, so creating an instance of ComplexChild isn’t a big deal; the only thing it needs to figure out is which constructor to pick. When multiple public constructors are available, it always picks the one with the fewest number of arguments – in this case ComplexChild(string).

Obviously, it then needs to create an anonymous string value. For primitive types like strings, numbers and booleans, AutoFixture has custom algorithms for value creation. Since I’ll cover those mechanisms later, suffice it to say that Constrained Non-Determinism is used to create an anonymous string.

At this point, AutoFixture has all the information it needs, and it can now return a properly initialized instance of ComplexParent.

This ability to create instances of almost arbitrarily complex types is a real time-saver: That, more than the ability to create single strings or numbers, was the reason I originally created AutoFixture, since I got tired of initializing complex object graphs just to satisfy some API that the Test Fixture requires.

It also has the additional advantage that it hides all the irrelevant object creation code that the Test Fixture needs, but which isn’t relevant for the test at hand.

posted on Tuesday, March 24, 2009 9:22:49 PM (Romance Standard Time, UTC+01:00)  #    Comments [2] Trackback
# Sunday, March 22, 2009

It gives me great pleasure to announce my latest project: AutoFixture!

What is AutoFixture?

In essence, AutoFixture is a library that creates Anonymous Variables for you when you write unit tests. The intention is that it should enhance your productivity when you do Test-Driven Development – as it has done mine.

Instead of using mental resources on creating Anonymous Variables, AutoFixture can do it for you. By default, it uses Constrained Non-Determinism, but you can configure it to behave differently if you wish.

Here’s a very basic example:

[TestMethod]
public void IntroductoryTest()
{
    // Fixture setup
    Fixture fixture = new Fixture();
 
    int expectedNumber = fixture.CreateAnonymous<int>();
    MyClass sut = fixture.CreateAnonymous<MyClass>();
    // Exercise system
    int result = sut.Echo(expectedNumber);
    // Verify outcome
    Assert.AreEqual<int>(expectedNumber, result, "Echo");
    // Teardown
}

The Fixture class is your main entry point to AutoFixture. You can use it as is, customize it, or derive from it as you please; it makes a great base class for a Fixture Object.

The expectedNumber variable may be an Explicit Expectation, but its value is Anonymous, so instead of coming up with a number ourselves, we can let the CreateAnonymous<T> method do it for us.

This method can create instances of most CLR types as long as they have a public constructor (it uses Reflection), but for many primitive types (like Int32), it has specific, customizable algorithms for creating values using Constrained Non-Determinism.

When creating the SUT, we can also use Fixture as an excellent SUT Factory. Since it will do whatever it can to create an instance of the type you ask for, it is pretty robust if you decide to refactor the SUT’s constructor.

The above example only hints at what AutoFixture can do. Since the example is very simple, it may be hard to immediately understand its value, so in future posts I will expand on specific AutoFixture features and principles.

Getting started with AutoFixture is as simple as downloading it from CodePlex and referencing the assembly in Visual Studio.

posted on Sunday, March 22, 2009 7:50:54 AM (Romance Standard Time, UTC+01:00)  #    Comments [2] Trackback