Autofixture customizations: provide constructor parameter

半腔热情 提交于 2020-01-01 07:32:44

问题


I have the following class:

class Foo
{
    public Foo(string str, int i, bool b, DateTime d, string str2)
    {
         .....
    }
}

I'm creating a Foo with AutoFixture:

var foo = fixture.Create<Foo>();

but I want AutoFixture to provide a known value for the str2 parameter and use the default behavior for every other parameter.

I tried implementing a SpecimenBuilder but I can't find a way to get the metadata associated with the request to know that I'm being called from the Foo constructor.

Is there any way to achieve this?


回答1:


As answered here you can have something like

public class FooArg : ISpecimenBuilder
{
    private readonly string value;

    public FooArg(string value)
    {
        this.value = value;
    }

    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as ParameterInfo;
        if (pi == null)
            return new NoSpecimen(request);

        if (pi.Member.DeclaringType != typeof(Foo) ||
            pi.ParameterType != typeof(string) ||
            pi.Name != "str2")
            return new NoSpecimen(request);

        return value;
    }
}

and then you can register it like this

var fixture = new Fixture();
fixture.Customizations.Add(new FooArg(knownValue));

var sut = fixture.Create<Foo>();


来源:https://stackoverflow.com/questions/26149618/autofixture-customizations-provide-constructor-parameter

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