logo

RegularExpressionAttribute support in AutoFixture

Starting with AutoFixture version 2.6, when this attribute is applied on a data field AutoFixture will try to generate a value that matches the specified regular expression.

Let’s take as an example the following type:

public class RegularExpressionValidatedType
{
    // Allow up to 40 uppercase and lowercase.
    [RegularExpression("^[a-zA-Z''-'\s]{1,40}$")]
    public string Name { get; set; }

    [RegularExpression("^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$")]
    public string Url { get; set; }
}

Prior to AutoFixture version 2.6, AutoFixture by default would generate an instance of the above type with it’s properties containing GUID values.

From now on, AutoFixture can handle requests with regular expressions through the RegularExpressionAttribute class.

Under the hood

The idea behind this new feature is that members of a Regular Expression (regex) can be generated by first transforming the regex into a finite-state machine, particularly a DFA

You may also watch a short, introductory, video on the subject here. (Although it is for Rex, I find it very descriptive.)

The current implementation uses internally the algorithms provided by the dk.brics.automaton and Xeger packages.

Using without AutoFixture

This feature is also available stand-alone via the Fare library.