Can I tell AutoFixture to call some base method for all instances of classes that inherit from it?

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

  •  21-07-2021
  •  | 
  •  

Question

I have an Entity class that exposes a read-only Id property. This property gets set via an ORM after it is saved (no longer transient). I'd like to have AutoFixture call a method that sets the Id property internally for all instances of classes that inherit from Entity.

There are several customizations being applied to the fixture that register the creation of a select few of these descendants, so I'd like to ensure they run first. I guess the ideal situation would be to allow me to run some modification code to an anonymous value before it is returned from the fixture.

For example, when I call fixture.CreateAnonymous<Order>(), there would be some other customization (or the like) that can modify that Order instance before it is returned.

This modification would not intercept just Order, but any Entity descendant.

Was it helpful?

Solution

After solving this with a custom class that extended Fixture, I took the advice of both Ruben and Mark. I created the same basic solution via an ICustomization that is applied via my existing custom CompositeCustomization. Here is the new customization for setting my entity Ids before instances are returned via CreateAnonymous.

public class SetEntityIdCustomization : ICustomization {
    public void Customize(IFixture fixture) {
        var engine = ((Fixture)fixture).Engine;
        fixture.Customizations.Add(new Postprocessor(
            engine, o => {
                var entity = o as BaseEntity;
                if (entity == null || !entity.IsTransient()) {
                    return;
                }

                entity.SetId(fixture.CreateAnonymous<Guid>());
            }));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top