Fork me on GitHub
Nikos Baxevanis

URI support in AutoFixture

Starting with version 2.10.0, AutoFixture supports the creation of Uniform Resource Identifiers and the Uri type.

It is now possible to create an anonymous variable for Uri as with any other common type:

var fixture = new Fixture();
var uri = fixture.CreateAnonymous<Uri>();
// Prints -> scheme://257eb39a-8305-4d13-a7cb-0c481b78809a/

By default, both the scheme name and the authority part are obtained from the context. A custom UriScheme class represents the URI scheme name while the authority part is an anonymous variable of type string.

Example URIs along with their component parts can be found here. Since both parts are received from the context, they can be easily customized.

Supplying a custom scheme name

The UriScheme type provides by default the name "scheme". However, by injecting a specific instance of this type we can easily override it with something else (e.g. "http").

var fixture = new Fixture();
fixture.Inject(new UriScheme("http"));
var uri = fixture.CreateAnonymous<Uri>(); 
// Prints -> http://abc9f406-16f2-4e06-b6f9-0750dc115ac3/

Supplying a custom authority

This is preferred only when each test constructs its own instance of the Fixture type since this change will apply for all the strings received from the context.

Since the authority part is a string received from the context, it is possible to modify the base of all strings and get the desired name for the authority.

var fixture = new Fixture();
fixture.Customizations.Add(
    new StringGenerator(() => "autofixture.codeplex.com"));
var uri = fixture.CreateAnonymous<Uri>(); 
// Prints -> scheme://autofixture.codeplex.com/

Supplying a custom Uri

As with any other generated specimen, it is possible to completely take over it's creation. Using a custom ISpecimenBuilder type, each time a Uri is requested, a predefined Uri will be returned.

public class CustomUriBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        if (request == typeof(Uri))
        {
            return new Uri("http://autofixture.codeplex.com");
        }

        return new NoSpecimen(request);
    }
}

var fixture = new Fixture();
fixture.Customizations.Add(new CustomUriBuilder());
var uri = fixture.CreateAnonymous<Uri>(); 
// Prints -> http://autofixture.codeplex.com/

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