λ>_

RegularExpressionAttribute support in AutoFixture

11 December 2011

Continuing the support of DataAnnotations as described here and here, there is now added support for the RegularExpressionAttribute class.

Starting with version 2.6.0, 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 version 2.6.0 if we request an anonymous instance from AutoFixture, by default we would get back an instance of the above type with it's properties containing values similar to those below.

Prior verion 2.6.0

However, from version 2.6.0 AutoFixture can handle requests with regular expressions, through the RegularExpressionAttribute class, by issuing a new request for the specified regular expression pattern.

After verion 2.6.0

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 Deterministic finite automaton

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.

An automatically published release created from the latest successful build can be downloaded from here. The latest version is also live on NuGet.