Search code examples
c#autofixture

How to create a Generic Model without Id for AutoFixture?


I am using Autofixture to autogenerate data for my tests in XUnit.

At the moment, I have the below customize method - this is an implementation of ICustomization:

    public void Customize(IFixture fixture)
    {
        fixture.Customize<Product>(composer =>
            composer.Without(e => e.Id));
    }

Is it possible have like a generic type - e.g instead of Product, where I can pass any Model?


Solution

  • This should be possible by using a custom specimen builder:

    public class NoIdSpecimenBuilder : ISpecimenBuilder
        {
            public object Create(object request, ISpecimenContext context)
            {
                var propertyInfo = request as System.Reflection.PropertyInfo;
                if (propertyInfo != null &&
                    propertyInfo.Name.Equals("Id"))
                {
                    return new OmitSpecimen();
                }
    
                var fieldInfo = request as System.Reflection.FieldInfo;
                if (fieldInfo != null &&
                    fieldInfo.Name.Equals("Id"))
                {
                    return new OmitSpecimen();
                }
    
                return new NoSpecimen();
            }
        }
    

    This will stop autofixture from trying to generate a value for all properties that has the name "Id".

    the code above is a slightly edited example from: https://thomasardal.com/customizations-for-autofixture-my-new-best-friend/

    I have added the ability to not only ignore properties, but also fields. (If you are sure you always use properties and never fields, you can delete this part)

    Oh and the specimen builder is added to autofixture like this:

    fixture.Customizations.Add(new NoIdSpecimenBuilder());