URI support in AutoFixture

Apr 19, 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();
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.

Using the Web API Dependency Resolver with Castle Windsor

Mar 16, 2012

The code in this post requires the ASP.NET MVC 4 Beta. If you use the RC version use the code from this post.

Update: Mark Seemann has provided a great post on this subject.

In this post I will discuss a possible solution for having Castle Windsor resolving types for both MVC controllers and Web API controllers. Since the former is well known I will focus mostly on the Web API part.

A team building a mobile web application uses the ASP.NET MVC stack combined with another web services framework. With the release of the Beta version of ASP.NET MVC 4 they decided to give Web API a try (side by side with MVC controllers) and see if it fits their needs.

The Controller-derived types are used only for rendering the views (the code is written in JavaScript) while the ApiController-derived types are used for returning  data to the client.

The DependencyResolver class provides a method called SetResolver which acts as a registration point for resolving dependencies.

Be careful as there are more than one DependencyResolver types. One defined in System.Web.Mvc namespace and one defined in System.Web.Http namespace. We need the latter here.

Once we define the delegates and set a breakpoint we can see what types the framework requests.

At first an instance of the IHttpControllerFactory type is requested:

IHttpControllerFactory type is requested

Followed by a request for an instance of the ILogger type and so on.

ILogger type is requested

The first thing we want to do is to create a type implementing the IHttpControllerFactory interface.

using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using Castle.MicroKernel;

internal class WindsorHttpControllerFactory : IHttpControllerFactory
{
    private readonly HttpConfiguration configuration;
    private readonly IKernel kernel;

    public WindsorHttpControllerFactory(
        HttpConfiguration configuration, 
        IKernel kernel)
    {
        this.configuration = configuration;
        this.kernel = kernel;
    }

    public IHttpController CreateController(
        HttpControllerContext controllerContext, 
        string controllerName)
    {
        var controller = this.kernel.Resolve<IHttpController>(controllerName);

        controllerContext.Controller = controller;
        controllerContext.ControllerDescriptor = new HttpControllerDescriptor(
            this.configuration, 
            controllerName, 
            controller.GetType());

        return controllerContext.Controller;
    }

    public void ReleaseController(IHttpController controller)
    {
        this.kernel.ReleaseComponent(controller);
    }
}

Note that inside the WindsorHttpControllerFactory class the CreateController method  takes a string for the name of the controller. That means we need to use the Windsor's Named method to set a name for each controller registration. (We can also trim the "Controller" part from the name and also pluralize the remaining part.)

foreach (Type controller in typeof(OrderController).Assembly.GetTypes()
    .Where(type => typeof(IHttpController).IsAssignableFrom(type)))
{
    // https://github.com/srkirkland/Inflector/
    string name = Inflector.Pluralize(
        controller.Name.Replace("Controller", ""));

    container.Register(Component
        .For(controller)
        .Named(name)
        .LifestylePerWebRequest());
}

Let's also create a NullLogger implementing the ILogger interface.

using System;
using System.Diagnostics;
using System.Web.Http.Common;

internal class NullLogger : ILogger
{
    public void Log(string category, TraceLevel level, 
        Func<string> messageCallback)
    {
    }

    public void LogException(string category, TraceLevel level, 
        Exception exception)
    {
    }
}

For all the other instances that the framework requests there are default implementations in the System.Web.* assemblies and we can now create a Windsor Installer to encapsulate the registration logic.

using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Common;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Metadata;
using System.Web.Http.Metadata.Providers;
using System.Web.Http.ModelBinding;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

internal class WebApiInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IHttpControllerFactory>()
               .ImplementedBy<WindsorHttpControllerFactory>()
               .LifestyleSingleton(),

            Component.For<ILogger>()
               .ImplementedBy<NullLogger>()
               .LifestyleSingleton(),

            Component.For<IFormatterSelector>()
               .ImplementedBy<FormatterSelector>()
               .LifestyleSingleton(),

            Component.For<IHttpControllerActivator>()
               .ImplementedBy<DefaultHttpControllerActivator>()
               .LifestyleTransient(),

            Component.For<IHttpActionSelector>()
               .ImplementedBy<ApiControllerActionSelector>()
               .LifestyleTransient(),

            Component.For<IActionValueBinder>()
               .ImplementedBy<DefaultActionValueBinder>()
               .LifestyleTransient(),

            Component.For<IHttpActionInvoker>()
               .ImplementedBy<ApiControllerActionInvoker>()
               .LifestyleTransient(),

            Component.For<ModelMetadataProvider>()
               .ImplementedBy<CachedDataAnnotationsModelMetadataProvider>()
               .LifestyleTransient(),

            Component.For<HttpConfiguration>()
               .Instance(GlobalConfiguration.Configuration));
    }
}

In the Application_Start method we add the installer and set the delegates for the SetResolver method. That way when the framework requests an IHttpControllerFactory instance, Windsor will supply the one we created earlier.

this.container = new WindsorContainer()
    .Install(new WebApiInstaller());

GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
    serviceType => container.Resolve(serviceType),
    serviceType => container.ResolveAll(serviceType).Cast<object>());

In order to have Windsor resolve regular controllers (side by side) we can create and add another installer as well as an implementation of the IControllerFactory interface.

this.container = new WindsorContainer()
    .Install(new WebMvcInstaller())
    .Install(new WebApiInstaller());

GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
    serviceType => container.Resolve(serviceType),
    serviceType => container.ResolveAll(serviceType).Cast<object>());

ControllerBuilder.Current.SetControllerFactory(
    new WindsorControllerFactory(this.container));

Finally, a gist with all the source code can be found here.

References:

Dynamic Proxy overriding Equals in AutoFixture Likeness

Feb 20, 2012

From version 2.9.0 of AutoFixture, the Likeness class contains a new feature for creating a dynamic proxy that overrides Equals on the destination type.

As an example, we want to compare instances of the following types:

public class DoubleParameterType<T1, T2>
{
    public DoubleParameterType(T1 parameter1, T2 parameter2)
    {
        this.Parameter1 = parameter1;
        this.Parameter2 = parameter2;
    }

    public T1 Parameter1 { get; private set; }
    public T2 Parameter2 { get; private set; }
}

public class SingleParameterType<T>
{
    public SingleParameterType(T parameter)
    {
        this.Parameter = parameter;
    }

    public T Parameter { get; private set; }
}

We can have the following syntax (prior to version 2.9.0):

[Fact]
public void TestWithLikeness()
{
    // Fixture setup
    var value = new DoubleParameterType<int, double>(1, 2.0);

    Likeness<DoubleParameterType<int, double>, SingleParameterType<int>> sut 
        = value.AsSource()
               .OfLikeness<SingleParameterType<int>>();
            
    // Exercise system
    var result = sut.Equals(value);
    // Verify outcome
    Assert.True(result);
}

However, from version 2.9.0 there is also a new CreateProxy method on Likeness which returns a proxy of the destination type overriding Equals with Likeness's instance of IEqualityComparer (the SemanticComparer class):

[Fact]
public void TestWithLikenessProxy()
{
    // Fixture setup
    var value = new DoubleParameterType<int, double>(1, 2.0);
            
    SingleParameterType<int> sut
        = value.AsSource()
               .OfLikeness<SingleParameterType<int>>()
               .CreateProxy();
            
    // Exercise system
    var result = sut.Equals(value);
    // Verify outcome
    Assert.True(result);
}

Below is also an example, where we need to verify that an expectation was met:

public class Bar
{
    public string Zip { get; set; }
}

public class Foo
{
    public Bar Bar { get; private set; }

    public void DoSomething(ISomeContext ctx)
    {
        this.Bar = new Bar { Zip = "12345" };
        ctx.DoSomething(this.Bar);
    }
}

public interface ISomeContext
{
    void DoSomething(object request);
}

[Fact]
public void Test()
{
    var foo = new Foo();
    var ctx = new Mock<ISomeContext>();
    foo.DoSomething(ctx.Object);

    var bar = new Bar().AsSource().OfLikeness<Bar>().CreateProxy();
    bar.Zip = "12345";

    ctx.Verify(x => x.DoSomething(bar));
}

Although the new Bar instance is created inside the DoSomething method, we can pass a proxied Bar instance on the mock's Verify method.

Internally, a custom Proxy Generator was written which also supports types with non-parameterless constructors. In order to create proxies of such types, the values from the source have to be compatible with the parameters on the destination constructor. (The mapping between the two is made possible by using the same semantic heuristics, as the default semantic comparison.)

Auto-Mocking with FakeItEasy and AutoFixture

Dec 14, 2011

AutoFixture can become an auto-mocking container using Moq (described here) and Rhino Mocks (described here).

In addition to the above auto-mocking features it is now possible to use FakeItEasy.

To install AutoFixture with Auto Mocking using FakeItEasy, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoFakeItEasy

To use it, add an AutoFakeItEasyCustomization to the Fixture instance:

var fixture = new Fixture()
    .Customize(new AutoFakeItEasyCustomization());

Here is a typical usage inside a test method which will automatically create mocked instances using FakeItEasy:

var fixture = new Fixture()
    .Customize(new AutoFakeItEasyCustomization());
var result = fixture.CreateAnonymous<IInterface>();

To explicitly use FakeItEasy inside a test you need to Freeze it first:

[Fact]
public void FixtureCanFreezeFake()
{
    // Fixture setup
    var fixture = new Fixture()
        .Customize(new AutoFakeItEasyCustomization());
    var dummy = new object();
    var fake = fixture.Freeze<Fake<IInterface>>();
    fake.CallsTo(x => x.MakeIt(dummy))
        .Returns(null);
    // Exercise system
    var result = fixture.CreateAnonymous<IInterface>();
    result.MakeIt(dummy);
    // Verify outcome
    A.CallTo(() => result.MakeIt(dummy)).MustHaveHappened();
    // Teardown
}

The above example can be made even more elegant by using AutoData theories:

[Theory, AutoFakeItEasyData]
public void FixtureCanFreezeFake([Frozen]Fake<IInterface> fake, IInterface sut)
{
    var dummy = new object();
    sut.MakeIt(dummy);
    A.CallTo(() => sut.MakeIt(dummy)).MustHaveHappened();
}

Update (2014/02/28): It is also possible to use the [Frozen] attribute on the IInterface directly, as Mark Seemann commented here.

Below is the code for the AutoFakeItEasyDataAttribute class:

public class AutoFakeItEasyDataAttribute : AutoDataAttribute
{
    public AutoFakeItEasyDataAttribute()
        : base(new Fixture().Customize(new AutoFakeItEasyCustomization()))
    {
    }
}

An automatically published release created from the latest successful build can also be downloaded from here.

RegularExpressionAttribute support in AutoFixture

Dec 11, 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.

subscribe via RSS