logo

Heuristics for Static Factory Methods in AutoFixture

Here is a type with a private constructor:

public class TypeWithFactoryMethod
{
    private TypeWithFactoryMethod()
    {
    }

    public static TypeWithFactoryMethod Create()
    {
        return new TypeWithFactoryMethod();
    }

    public static TypeWithFactoryMethod Create(object argument)
    {
        return new TypeWithFactoryMethod();
    }
}

In order to create an instance of that type we have to call one of it's static factory methods, for example:

var instance = TypeWithFactoryMethod.Create();

If we try to create an Anonymous Variable with AutoFixture right now (version 2.1) it will throw an exception since there are no public constructors:

var fixture = new Fixture();
var result = fixture.CreateAnonymous<TypeWithFactoryMethod>();

Using the latest version from trunk (and on the next public release) the above code will work. It will successfully return an instance of the type by using a set of heuristics that enable AutoFixture to search for static factory methods.

The latest build (including strong names) can be downloaded from here.