Force AutoFixture to use the greediest constructor

╄→гoц情女王★ 提交于 2019-11-30 08:04:22

This is certainly possible.

To change the strategy for a single type (MyClass):

fixture.Customize<MyClass>(c => c.FromFactory(
    new MethodInvoker(
        new GreedyConstructorQuery())));

To change the strategy across the board:

fixture.Customizations.Add(
    new MethodInvoker(
        new GreedyConstructorQuery()));

As it turns out, however, using GreedyConstructorQuery across the board is most likely problematic, as the following code snippet demonstrates. Imagine a class with this constructor:

public Foo(string name)
{
    this.name = name;
}

This test will throw an exception:

[Test]
public void GreedyConstructor()
{
    Fixture fixture = new Fixture();
    fixture.Customizations.Add(new MethodInvoker(new GreedyConstructorQuery()));

    Foo foo = fixture.CreateAnonymous<Foo>();
}

The exception thrown is:

Ploeh.AutoFixture.ObjectCreationException : AutoFixture was unable to create an instance from System.SByte*, most likely because it has no public constructor, is an abstract or non-public type.

So what's that about the SByte*? There's no SByte* in Foo...

Well, yes there is. By placing the MethodInvoker in Customization, it overrides all default creation strategies, including the one for strings. Instead, it goes looking for the greediest constructor for string and that is:

public String(sbyte* value, int startIndex, int length, Encoding enc);

And there's the sbyte*...


It's still possible to replace the modest constructor selection algorithm with a greedy algorithm, it's just a tad more involved than I first realized.

What you can do is this:

Write a small class like this one:

public class GreedyEngineParts : DefaultEngineParts
{
    public override IEnumerator<ISpecimenBuilder> GetEnumerator()
    {
        var iter = base.GetEnumerator();
        while (iter.MoveNext())
        {
            if (iter.Current is MethodInvoker)
                yield return new MethodInvoker(
                    new CompositeMethodQuery(
                        new GreedyConstructorQuery(),
                        new FactoryMethodQuery()));
            else
                yield return iter.Current;
        }
    }
}

and create the Fixture instance like this:

Fixture fixture = new Fixture(new GreedyEngineParts());

That should work.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!