moodmosaic (Nikos Baxevanis)
Blog - About - Open Source - Bookmarks - Tags

Heuristics for Static Factory Methods in AutoFixture

Thursday, 25 August 2011

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.

━━━

This post has been filed under #autofixture

Feedback

Have feedback on this page? Let @nikosbaxevanis know on twitter. Need help or found a bug? Contact me.


© 2011-2018 Nikos Baxevanis. All written content on this site is provided under a Creative Commons ShareAlike license. All code is provided under a MIT license unless otherwise stated.