Search code examples
autofixture

AutoFixture and Custom DataAnnotations


I'm using AutoFixture in my unit and integration tests and ran into a problem. I'm generating data transfer objects and some of those classes have DataAnnotation attributes (some of which are custom) on the properties. AutoFixture sees those and doesn't generate data for them, presumably because it is unsure what data it is expecting.

An example of a custom validation attribute I'm using:

public class Person 
{
   public string FullName { get; set; }

   [Enum("M", "F")]
   public string Gender { get; set; }
}

public class EnumAttribute : ValidationAttribute
{
   public EnumAttribute(params string[] allowedStrings)
    {
        if (allowedStrings == null || allowedStrings.Length == 0)
            throw new ArgumentException("allowedStrings");
        AllowNull = true;
        AllowedStrings = allowedStrings;
        ErrorMessage = "The field '{0}' is invalid. Allowed strings are " + string.Join(", ", AllowedStrings);
    }

    // ... implementation
}

It just restricts a provided string to certain value (I couldn't use a straight up enum for other reasons).

How could I customize AutoFixture to create the appropriate data?


Solution

  • Currently, AutoFixture supports the following validation attributes:

    To support a custom validation attribute you'll have to extrapolate from one of the following groups:

    And then, you'll have to add the newly created Relay and Generator classes as Customizations.