Orlando Osorio
Orlando Osorio

Reputation: 3125

Autofixture customizations: provide constructor parameter

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?

Upvotes: 40

Views: 27912

Answers (2)

bombek
bombek

Reputation: 584

This answers the similar problem but with custom type e.g. MyType. When given:

class Foo
{
    public Foo(string str, MyType myType)
    {
         .....
    }
}

class MyType
{
    private readonly string myType;

    public MyType(string myType)
    {
        this.myType = myType
    }
}

You can call

fixture.Customize<MyType>(c => c.FromFactory(() => new MyType("myValue")));
var foo = fixture.Build<Foo>();

Upvotes: 9

Orlando Osorio
Orlando Osorio

Reputation: 3125

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>();

Upvotes: 17

Related Questions