moodmosaic (Nikos Baxevanis)
Blog - About - Open Source - Bookmarks - Tags

URI support in AutoFixture

Thursday, 19 April 2012

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();
    new StringGenerator(() => ""));
var uri = fixture.CreateAnonymous<Uri>();
// Prints -> scheme://

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("");

        return new NoSpecimen(request);

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

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


This post has been filed under #autofixture


Have feedback on this page? Let @nikosbaxevanis know on twitter. Need help or found a bug? Contact me.

© 2011-2018 Nikos Baxevanis. All written content on this site is provided under a Creative Commons ShareAlike license. All code is provided under a MIT license unless otherwise stated.