Specifying [readonly] property values [via ctor args] when instantiating [immutable] objects with AutoFixture

StackOverflow https://stackoverflow.com/questions/20808755

Question

My test requires that I set the Response property on an immutable Rsvp object (see below) to a specific value.

public class Rsvp
{
    public string Response { get; private set; }

    public Rsvp(string response)
    {
        Response = response;
    }
}

I initially tried to do this using Build<Rsvp>().With(x => x.Rsvp, "Attending"), but realized this only supports writable properties.

I replaced that with Build<Rsvp>().FromFactory(new Rsvp("Attending")). This works, but is cumbersome for more complex objects where it doesn't matter what some of the properties are.

For instance, if the Rsvp object had a CreatedDate property, this method of instantiating the object would force me to write Build<Rsvp>().FromFactory(new Rsvp("Attending", fixture.Create<DateTime>())).

Is there a way to only specify values for meaning properties for an immutable object?

Was it helpful?

Solution

AutoFixture was originally build as a tool for Test-Driven Development (TDD), and TDD is all about feedback. In the spirit of GOOS, you should listen to your tests. If the tests are hard to write, you should consider your API design. AutoFixture tends to amplify that sort of feedback.

Frankly, immutable types are a pain in C#, but you can make it easier to work with a class like Rsvp if you take a cue from F# and introduce copy and update semantics. If you modify Rsvp like this, it's going to be much easier to work with overall, and thus, as a by-product, also to unit test:

public class Rsvp
{
    public string Response { get; private set; }

    public DateTime CreatedDate { get; private set; }

    public Rsvp(string response, DateTime createdDate)
    {
        Response = response;
        CreatedDate = createdDate;
    }

    public Rsvp WithResponse(string newResponse)
    {
        return new Rsvp(newResponse, this.CreatedDate);
    }

    public Rsvp WithCreatedDate(DateTime newCreatedDate)
    {
        return new Rsvp(this.Response, newCreatedDate);
    }
}

Notice that I've add two WithXyz methods, that return a new instance with that one value changed, but all other values held constant.

This would enable you to create an instance of Rsvp for testing purposed like this:

var fixture = new Fixture();
var seed = fixture.Create<Rsvp>();
var sut = seed.WithResponse("Attending");

or, as a one-liner:

var sut = new Fixture().Create<Rsvp>().WithResponse("Attending");

If you can't change Rsvp, you can add the WithXyz methods as extension methods.

Once you've done this about a dozen times, you get tired of it, and it's time to make the move to F#, where all that (and more) is built-in:

type Rsvp = {
    Response : string
    CreatedDate : DateTime }

You can create an Rsvp record with AutoFixture like this:

let fixture = Fixture()
let seed = fixture.Create<Rsvp>()
let sut = { seed with Response = "Attending" }

or, as a one-liner:

let sut = { Fixture().Create<Rsvp>() with Response = "Attending" }

OTHER TIPS

As long as the Response property is readonly*, you can define a custom SpecimenBuilder for the Rsvp type:

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

        if (pi.ParameterType != typeof(string) || pi.Name != "response")
            return new NoSpecimen();

        return "Attending";
    }
}

The following test passes:

[Fact]
public void ResponseIsCorrect()
{
    var fixture = new Fixture();
    fixture.Customizations.Add(new RsvpBuilder());
    var sut = fixture.Create<Rsvp>();

    var actual = sut.Response;

    Assert.Equal("Attending", actual);
}

* If for some reason the Response property becomes writable you can follow the solution in this answer.

Extending Nikos´ answer, we can generalize the customization to work with any property as such:

public class OverridePropertyBuilder<T, TProp> : ISpecimenBuilder
{
    private readonly PropertyInfo _propertyInfo;
    private readonly TProp _value;

    public OverridePropertyBuilder(Expression<Func<T, TProp>> expr, TProp value)
    {
        _propertyInfo = (expr.Body as MemberExpression)?.Member as PropertyInfo ??
                        throw new InvalidOperationException("invalid property expression");
        _value = value;
    }

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

        var camelCase = Regex.Replace(_propertyInfo.Name, @"(\w)(.*)",
            m => m.Groups[1].Value.ToLower() + m.Groups[2]);

        if (pi.ParameterType != typeof(TProp) || pi.Name != camelCase)
            return new NoSpecimen();

        return _value;
    }
}

But then we need custom extension methods to make it easier to use:

public class FixtureCustomization<T>
{
    public Fixture Fixture { get; }

    public FixtureCustomization(Fixture fixture)
    {
        Fixture = fixture;
    }

    public FixtureCustomization<T> With<TProp>(Expression<Func<T, TProp>> expr, TProp value)
    {
        Fixture.Customizations.Add(new OverridePropertyBuilder<T, TProp>(expr, value));
        return this;
    }

    public T Create() => Fixture.Create<T>();
}

public static class CompositionExt
{
    public static FixtureCustomization<T> For<T>(this Fixture fixture)
        => new FixtureCustomization<T>(fixture);
}

we then use it in your example as:

var obj = 
  new Fixture()
    .For<Rsvp>()
    .With(x => x.Response, "Attending")
    .Create();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top