2

I have a use case where I want AutoFixture to build my object using the default method, but then I want to add some post handling to it because there are certain properties I then need to set dynamically after the object has been built. However I want the posthandling to occur on all objects that derive from a specific type. Is there any way to do this using AutoFixture?

Kayode Leonard
  • 425
  • 5
  • 12

1 Answers1

1

AutoFixture automatically populates writable properties so you don't have to do anything in order to enable that. If you want some of the properties to be treated in a special way, you can define an ISpecimenBuilder for such properties, e.g.

public class StreetNameBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;
        if (pi == null || pi.Name != "StreetName" || pi.PropertyType != typeof(string))
            return new NoSpecimen();

        return "Baker Street"; // Your custom value goes here.
    }
}

Such a builder, when registered, handles all StreetName properties of the type string, regardless of on which class that property is defined. If you want to target properties that are defined on a class that derives from a particular base class, then you can inspect pi for that information as well.

You need to register the builder with a Fixture instance, for example like this:

fixture.Customizations.Add(new StreetNameBuilder());
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736