Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofixture customizations: provide constructor parameter

Tags:

c#

autofixture

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?

like image 286
Orlando William Avatar asked Oct 01 '14 20:10

Orlando William


2 Answers

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>();
like image 78
2 revs Avatar answered Sep 22 '22 17:09

2 revs


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>();
like image 7
bombek Avatar answered Sep 22 '22 17:09

bombek