# Thursday, November 26, 2009

In unit testing an important step is to exercise the SUT. The member you want to invoke is often a method that takes one or more parameters, but in some test cases you don't care about the values of those parameters – you just want to invoke the method.

You can always make up one or more Dummy parameters and pass them to the method in question, but you could also use one of AutoFixture's Do convenience methods. There are several overloads that all take delegates that specify the action in question while providing you with Dummies of any parameters you don't care about.

A good example is WPF's ICommand interface. The most prevalent method is the Execute method that takes a single parameter parameter:

void Execute(object parameter);

Most of the time we don't really care about the parameter because we only care that the command was invoked. However, we still need to supply a value for the parameter when we unit test our ICommand implementations. Obviously, we could just pass in a new System.Object every time, but why not let AutoFixture take care of that for us?

(You may think that new'ing up a System.Object is something you can easily do yourself, but imagine other APIs that require much more complex input parameters, and you should begin to see the potential.)

Here's a state-based unit test that verifies that the Message property of the MyViewModel class has the correct value after the FooCommand has been invoked:

[TestMethod]

public void FooWillUpdateMessage()

{

    // Fixture setup

    var fixture = new Fixture();

    var sut = fixture.CreateAnonymous<MyViewModel>();

    // Exercise system

    fixture.Do((object parameter) =>

        sut.FooCommand.Execute(parameter));

    // Verify outcome

    Assert.AreEqual("Foo", sut.Message, "Message");

    // Teardown

}

Notice how the Do method takes an Action<object> to specify the method to invoke. AutoFixture automatically supplies an instance for the parameter parameter using the same engine to create Anonymous variables that it uses for everything else.

The Do method in question is really a generic method with this signature:

public void Do<T>(Action<T> action);

There are also overloads that take two, three or four input parameters, corresponding to the available Action types available in the BCL.

These methods are simply convenience methods that allow you to express your test code more succinctly than you would otherwise have been able to do.

posted on Thursday, November 26, 2009 10:23:46 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, November 17, 2009

Daniel Frost has published a podcast where he discusses Dependency Injection with me. It's about half an hour long and in Danish. Hear it here.

posted on Tuesday, November 17, 2009 7:58:47 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback

When using Castle Windsor in web applications you would want to register many of your components with a lifestyle that is associated with a single request. This is the purpose of the PerWebRequest lifestyle.

If you try that with ASP.NET MVC on IIS7, you are likely to receive the following error message:

Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
Add '<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />' to the <httpModules> section on your web.config.

Unfortunately, following the instructions in the error message doesn't help. There's a discussion about this issue on the Castle Project Users forum, but the gist of it is that if you don't need to resolve components during application startup, this shouldn't be an issue, and indeed it isn't – it seems to be something else.

In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules instead of configuration/system.web/httpModules.

Although I haven't had the opportunity to dive into the technical details to understand why this works, this seems to solve the problem on both Windows Vista and Windows Server 2008.

posted on Tuesday, November 17, 2009 1:44:37 PM (Romance Standard Time, UTC+01:00)  #    Comments [2] Trackback
# Saturday, November 07, 2009

The following feature suggestion was recently posted in the AutoFixture Issue Tracker board:

"We're using AutoFixture to create random rows of data in our DB. A lot of times though, it creates strings that are too long for the database columns. It would be nice if the .With<string> method had an overload that took in a min/max length. We want the random data, but capped at a limit.

"fixture.Build<MyObject>.With(x = x.MyString, 0, 100);

"As an aside, this is for a project that uses Nhibernate and Fluent Nhibernate, which has these lengths already defined. I would be nice if AutoFixture could automatically pick up on that somehow."

I think such an feature is an excellent idea, but I don't think I will include in AutoFixture. Why not?

So far, I have kept the AutoFixture API pretty clean and very generic, and it is my belief that this is one of the main reasons it is so expressive and flexible. There are no methods that only work on specific types (such as strings), and I am reluctant to introduce them now.

In the last six months, I have identified a lot of specialized usage idioms that I would love to package into a reusable library, but I think that they will pollute the core AutoFixture API, so I'm going to put those in one or more optional 'add-on' libraries.

The ability to define strings that are constrained on length could be one such feature, but rather than wait for a helper library, I will show you have you can implement such a method yourself.

The first thing we need is a method that can create anonymous strings given length constraints. One possible implementation is this ConstrainedStringGenerator class:

public class ConstrainedStringGenerator
{
    private readonly int minimumLength;
    private readonly int maximumLength;
 
    public ConstrainedStringGenerator(int minimumLength, 
        int maximumLength)
    {
        if (maximumLength < 0)
        {
            throw new ArgumentOutOfRangeException("...");
        }
        if (minimumLength > maximumLength)
        {
            throw new ArgumentOutOfRangeException("...");
        }
 
        this.minimumLength = minimumLength;
        this.maximumLength = maximumLength;
    }
 
    public string CreateaAnonymous(string seed)
    {
        var s = string.Empty;
        while (s.Length < this.minimumLength)
        {
            s += GuidStringGenerator.CreateAnonymous(seed);
        }
        if (s.Length > this.maximumLength)
        {
            s = s.Substring(0, this.maximumLength);
        }
        return s;
    }
}

The CreateAnonymous method uses AutoFixture's GuidStringGenerator class to create anonymous strings of the required length. For this implementation I chose a basic algorithm, but I'm sure you can create one that is more sophisticated if you need it.

Th next thing we need to do is to implement the desired With method. That can be done with an extension method works on ObjectBuilder<T>:

public static class ObjectBuilderExtension
{
    public static ObjectBuilder<T> With<T>(
        this ObjectBuilder<T> ob,
        Expression<Func<T, string>> propertyPicker,
        int minimumLength,
        int maximumLength)
    {
        var me = (MemberExpression)propertyPicker.Body;
        var name = me.Member.Name;
        var generator =
            new ConstrainedStringGenerator(
                minimumLength, maximumLength);
        var value = generator.CreateaAnonymous(name);
        return ob.With(propertyPicker, value);
    }
}

The method takes the same input as ObjectBuilder<T>'s With method, plus the two integers that constrain the length. Note that the propertyPicker expression has been constrained to deal only with strings.

In this implementation, we use the ConstrainedStringGenerator class to generate the desired value for the property, where after we can use the existing With method to assign the value to the property in question.

This now allows us to write Build statements like the one originally requested:

var mc = fixture.Build<MyClass>()
    .With(x => x.SomeText, 0, 100)
    .CreateAnonymous();

The other part of the request, regarding NHibernate integration, I will leave to the interested reader – mostly because I have never used NHibernate, so I have no clue how to do it. I would, however, love to see a blog post with that addition.

This entire example is now part of the AutoFixture test suite, so if you are interested in looking at it in more detail, you can get it from the AutoFixture source code (available at CodePlex).

posted on Saturday, November 07, 2009 8:56:05 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback