Sunday, December 27, 2009

Argument validation in FakeItEasy

I created two more screencasts on FakeItEasy, these two are on the subject on argument validation, I’ve increased the font size and put some compressor on the audio to improve the quality a bit.

 

Saturday, December 26, 2009

The basics of FakeItEasy

I thought I’d take a stab at screencasts so here’s my first attempt, it’s a quick overview of the FakeItEasy framework:

(I would highly recommend that you watch it in HD-quality, otherwise the text will not be readable.)

Saturday, December 19, 2009

Configuring any call to an object

I’ve just updated the way to configure any call to faked objects in FakeItEasy, the syntax is new and also you can now configure return values.

Let’s say you have an interface providing localized text resources like this:

public interface ILocalizedResources
{
    string SomeText { get; }
    string SomeOtherText { get; }
}

When you fake this interface any of the properties would return null when not configured but you might have several tests that are dependant on that the values are non null strings but still you don’t want to have to configure each individual property in the set up of you fixture. Now you can do exactly that:

var resources = A.Fake<ILocalizedResources>();
Any.CallTo(resources).WithReturnType<string>().Returns("");

Of course you can still configure any call to do anything you want just as before, for example:

var resources = A.Fake<ILocalizedResources>();
Any.CallTo(resources).Throws(new Exception());

 

Technorati-taggar: ,,,,,,

Thursday, December 10, 2009

T4

No, not that crappy movie but Text Template Transformation Toolkit.

I’ve played around with T4 every now and then over the last year but I’ve struggled to find any really good source for learning more. I guess the man who stands out from the crowd is Oleg Sych who has blogged about it en masse.

I’m watching a new screen cast by him on Channel 9 right now and it’s really good so please check it out.

Thursday, November 26, 2009

New configuration syntax for FakeItEasy

I’ve implemented a new, cleaner simpler, ninja-deluxe-shiny-gold-plated-ultra-cool way of configuring fakes/stubs/mocks in FakeItEasy.

The news are two fold:

  1. Simpler call specifications
  2. Simpler argument validations

How’s this for simple?

public void Example()
{
    var serviceProvider = A.Fake<IServiceProvider>();
    var service = A.Fake<IWidgetFactory>();

    A.CallTo(() => serviceProvider.GetService(typeof(IWidgetFactory))).Returns(service);
}

No need for awkward lambda expressions where you have to split the configured method from the object that it’s called on.

Instead of:

serviceProvider.CallsTo(x => x.GetService(typeof(IWidgetFactory))

This reads better:

A.CallTo(() => serviceProvider.GetService(typeof(IWidgetFactory)))

As I mentioned argument validation has also become simpler, I mean, this is just childs play isn’t it?

A.CallTo(() => serviceProvider.GetService(A<Type>.Ignored)).Throws(new Exception());
A.CallTo(() => serviceProvider.GetService(A<Type>.That.Matches(_ => _.Name.StartsWith("A")))).Throws(new Exception());

The really cool thing is that you can define your own extension methods that provides validations for arguments, these extension will show up on the “That”-property, like this:

A<Type>.That.IsValidatedByMyVeryOwnExtensionMethod();
A<Type>.That.IsInSystemNamespace();
A<string>.That.SpellsMyName();

It can be whatever you want, this means that you can effectively provide your own DSL for argument validation.

I’m thinking about providing an “An” class as well so that you can write the more grammatically correct “An<object>.Ignored” rather than “A<object>.Ignored”, but I’m not sure it’s worth it, maybe it’s confusing, what do you think?

I’ll be blogging about argument validations and how to provide your own extension super easy soon.

Technorati-taggar: ,,,,,

Saturday, November 7, 2009

Fix that bug will ya? NO!

If there’s a bug in software I’ve created my knee jerk reaction is that I created that bug. The knee jerk reaction of some developers is “there must be a bug in the framework”, which of course turns out to be false 99.9999% of the times.

Yesterday I managed to track down a bug that had eluded me for a couple of weeks; an object graph that we’re serializing to the Asp.Net session (using state server) sometimes couldn’t be serialized. Every class that could possibly be contained in the graph was marked as serializable and also the error message wasn’t the one you get when you have a value that isn’t serializable in the graph. What I found was the following, we have classes similar to this:

public interface IPredicate
{
    bool Evaluate(object value);
}

[Serializable]
public class AtLeastPredicate
    : IPredicate
{
    private IComparable lowerBound;

    public AtLeastPredicate(IComparable lowerBound)
    {
        this.lowerBound = lowerBound;
    }

    public bool Evaluate(object value)
    {
        return this.lowerBound.CompareTo(value) <= 0;
    }
}

You’d think that you’d be able to serialize instances of the AtLeastPredicate-type right? As long as the “lowerBound” value it self is serializable you say. Yup, that should be it I say.

Let’s try that:

public class Program
{
    public static void Main(string[] arguments)
    {
        var atLeastString = new AtLeastPredicate("bar");
        atLeastString = SerializeAndDeserialize(atLeastString);

        Debug.Assert(atLeastString.Evaluate("foo"));
    }

    public static T SerializeAndDeserialize<T>(T value)
    {
        var formatter = new BinaryFormatter();

        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, value);

            stream.Seek(0, SeekOrigin.Begin);

            return (T)formatter.Deserialize(stream);
        }
    }
}

Yup, works like a charm as it should. So… What’s the problem? Well, let’s try that again:

public class Program
{
    public static void Main(string[] arguments)
    {
        var atLeastInt = new AtLeastPredicate(5);
        atLeastInt = SerializeAndDeserialize(atLeastInt);

        Debug.Assert(atLeastInt.Evaluate(10));
    }

    public static T SerializeAndDeserialize<T>(T value)
    {
        var formatter = new BinaryFormatter();

        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, value);

            stream.Seek(0, SeekOrigin.Begin);
            
            return (T)formatter.Deserialize(stream);
        }
    }
}

Not much difference there, we’ve changed from comparing strings to comparing ints, and of course ints are serializable too so there should be no problem. But there is, this code will fail:

image

Turns out that this is a bug in the .net framework:

 http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=91177 

Oh, well, I’ve created my share of bugs in my life so who am I to blame MS for doing that every once in a while. What I don’t get though is that this bug will not be fixed, I can’t really come up with a scenario where fixing this is a breaking change. Now, for sure, me not being able to come up with such a scenario doesn’t mean it doesn’t exist.

I created an easy workaround for this however and since I was going to use it in a couple of places I encapsulated it in a class of its own:

[Serializable]
public class SerializableComparableField
    : IComparable
{
    private object valueField;

    public SerializableComparableField(IComparable value)
    {
        this.Value = value;
    }

    public IComparable Value
    {
        get
        {
            return (IComparable)this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }

    public int CompareTo(object obj)
    {
        return this.Value.CompareTo(obj);
    }
}

Using this class in the AtLeastPredicate and anywhere else we need a field continaing IComparables that should be serializable.

[Serializable]
public class AtLeastPredicate
    : IPredicate
{
    private SerializableComparableField lowerBound;

    public AtLeastPredicate(IComparable lowerBound)
    {
        this.lowerBound = new SerializableComparableField(lowerBound);
    }

    public bool Evaluate(object value)
    {
        return this.lowerBound.CompareTo(value) <= 0;
    }
}

Sunday, November 1, 2009

Configuring fake objects on a global scale

In this post I’ll describe a way that lets you specify default configurations for specific types so that any time a fake of that type is created this default configuration will be applied.

In FakeItEasy there’s a concept called a fake object container represented by the interface IFakeObjectContainer which has two methods, one for resolving/creating fakes and one for configuring fakes, in this post I’m going to focus on the configuration part.

namespace FakeItEasy.Api
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// A container that can create fake objects.
    /// </summary>
    public interface IFakeObjectContainer
    {
        /// <summary>
        /// Creates a fake object of the specified type using the specified arguments if it's
        /// supported by the container, returns a value indicating if it's supported or not.
        /// </summary>
        /// <param name="typeOfFakeObject">The type of fake object to create.</param>
        /// <param name="arguments">Arguments for the fake object.</param>
        /// <param name="fakeObject">The fake object that was created if the method returns true.</param>
        /// <returns>True if a fake object can be created.</returns>
        bool TryCreateFakeObject(Type typeOfFakeObject, IEnumerable<object> arguments, out object fakeObject);

        /// <summary>
        /// Applies base configuration to a fake object.
        /// </summary>
        /// <param name="typeOfFakeObject">The type the fake object represents.</param>
        /// <param name="fakeObject">The fake object to configure.</param>
        void ConfigureFake(Type typeOfFakeObject, object fakeObject);
    }
}

Using the scoping feature you can actually plug in your own container for a given scope like this:

using (Fake.CreateScope(new MyOwnContainer()))
{ 
    
}

This means that within this scope your container will be used. Let’s focus on the ConfigureFake-method. This method will be called ANY time a fake object is created by FakeItEasy and lets us hook into the creation process and apply configuration to the generated fake object. This provides an easy way of defining default configuration for fakes of certain types which allows you to in your tests focus on configuring the values that are significant to the test.

At the moment the default container is a class called NullFakeObjectContainer, which I’m sure you can guess does exactly nothing. However, there is an assembly distributed in the latest versions named FakeItEasy.Mef.dll. If you in your test-project adds a reference to this assembly FakeItEasy will automatically pick this up and use the MefContainer as the default container. And this is where the fun begins.

The MEF assembly exposes two types that are significant to this feature, the most important one being IFakeConfigurator and the most used one being FakeConfigurator<T>.

namespace FakeItEasy.Mef
{
    using System;
    using System.ComponentModel.Composition;

    /// <summary>
    /// Provides configurations for fake objects of a specific type.
    /// </summary>
    [InheritedExport(typeof(IFakeConfigurator))]
    public interface IFakeConfigurator
    {
        /// <summary>
        /// The type the instance provides configuration for.
        /// </summary>
        Type ForType { get; }

        /// <summary>
        /// Applies the configuration for the specified fake object.
        /// </summary>
        /// <param name="fakeObject">The fake object to configure.</param>
        void ConfigureFake(object fakeObject);
    }
}

As you see this interface is tagged with the InheritedExportAttribute from MEF, which means that when you implement this interface in a type that type is automatically exported.

As I said the most used one is probably FakeConfigurator<T> which is a base implementation of this interface that lets you implement it very easily. Let’s say for example that you want to provide a common configuration for the HttpRequestBase type, all you do is create a class that inherits FakeConfigurator<HttpRequestBase> and by magic this is exported by MEF and included in the default container.

public class RequestConfiguration
    : FakeConfigurator<HttpRequestBase>
{
    public override void ConfigureFake(HttpRequestBase fakeObject)
    {
        Configure.Fake(fakeObject)
            .CallsTo(x => x.Form)
            .Returns(new NameValueCollection());

        Configure.Fake(fakeObject)
            .CallsTo(x => x.UserAgent)
            .Returns("Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13");

        Configure.Fake(fakeObject)
            .CallsTo(x => x.ContentEncoding)
            .Returns(Encoding.UTF8);

        Configure.Fake(fakeObject)
            .CallsTo(x => x.Url)
            .Returns(new Uri("http://foo.com/"));

        Configure.Fake(fakeObject)
            .CallsTo(x => x.RawUrl)
            .Returns(x => ((HttpRequestBase)x.FakedObject).Url.AbsoluteUri);

        Configure.Fake(fakeObject)
            .CallsTo(x => x.UrlReferrer)
            .Returns(new Uri("http://bar.com/"));
    }
}

Now any time you create a faked HttpRequestBase it will automatically be configured with this default configuration and you will only have to override this default configuration with specific values you need for your tests.

[TestFixture]
public class Tests
{

    [Test]
    public void Test_something_that_is_dependent_on_the_UserAgent()
    {
        var request = A.Fake<HttpRequestBase>();

        Console.Write(request.UserAgent); // Will print "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13"

        Configure.Fake(request)
            .CallsTo(x => x.UserAgent)
            .Returns("some other agent");

        Console.Write(request.UserAgent); // Will print "some other agent"
    }
}

Saturday, October 24, 2009

Asserting on exception messages in NUnit

It seems to me that a lot of developers has missed the fact that Assert.Throws<T> in NUnit actually returns the thrown exception which lets you assert on the message (and other properties of the exception). I wrote a response to a question on Stack Overflow which talks about this:

http://stackoverflow.com/questions/1609536/nunit-assert-throws

Saturday, September 5, 2009

Fake scopes explained

FakeItEasy has a scoping feature that lets you configure calls only within a scope or asserting that calls was made within a specific scope.

A scope implements IDisposable and the Dispose method closes the scope, this means that to create a scope you create a using statement for it:

using (Fake.CreateScope())
{
    // Do something within the scope...
}

Any calls configured within a scope are only valid within that scope, this means that you can override the behavior of a faked method for just a small part of your test, for example:

public void Configuring_calls_in_scope()
{
    var factory = A.Fake<IWidgetFactory>();

    factory.Configure().CallsTo(x => x.Create()).Returns(A.Fake<IWidget>());

    using (Fake.CreateScope())
    {
        factory.Configure().CallsTo(x => x.Create()).Throws(new Exception());

        // This will throw since the method was configured in this scope.
        factory.Create();
    }

    // This will return a fake widget as configured before entering the scope.
    var widget = factory.Create();
}

Scopes also affects what calls are visible when getting the calls made to a fake object, when you’re inside a child scope and use the Fake.GetCalls(foo)-method or the RecordedCalls-property on a Fake<T>-object only the calls made within that scope are visible. In an outer scope the calls made in the outer scope and any child scope are visible:

public void Getting_calls_in_scope()
{
    var factory = A.Fake<IWidgetFactory>();

    factory.Configure().CallsTo(x => x.Create()).Returns(A.Fake<IWidget>());

    var widget = factory.Create();

    // This will succeed since there was a call to the create method
    // in the current scope.
    Fake.Assert(factory).WasCalled(x => x.Create());

    using (Fake.CreateScope())
    {
        // This will produce 0, no calls were made to the create method 
        // in the current scope.
        int numberOfCalls = Fake.GetCalls(factory).Matching(x => x.Create());

        // This will throw:
        Fake.Assert(factory).WasCalled(x => x.Create());
    }

    using (Fake.CreateScope())
    {
        factory.Create();
    }

    // This will now return 2 since there was one call in the outer scope
    // and another one in the inner scope.
    int numberOfCalls = Fake.GetCalls(factory).Matching(x => x.Create());
}

The other way of faking it

I’ve added a new way to create fake objects in FakeItEasy. You might call the “traditional” way of doing it in FakeItEasy is the “Rhino-style”:

public static void TraditionalWay()
{
    var foo = A.Fake<IFoo>();
    foo.Configure().CallsTo(x => x.Baz()).Returns(10);

    int value = foo.Baz();

    Fake.Assert(foo).WasCalled(x => x.Baz());
}

When creating fakes in this way the returned faked object is of the type specified in the A.Fake-call, faking an IFoo returns an IFoo. When creating a fake the new way, which we might call the “Moq-style” you instead create a fake object that provides an api for configuring the faked object as well as a reference to the faked object:

public static void TheOtherWay()
{
    var foo = new Fake<IFoo>();
    foo.CallsTo(x => x.Baz()).Returns(10);

    int value = foo.FakedObject.Baz();

    foo.Assert().WasCalled(x => x.Baz());
}

Both styles are equally supported so that the developer can choose what ever style he/she is most comfortable with.

Saturday, August 22, 2009

Upcasting vs. downcasting

I always seem to forget which is which so I guess I’ll write it down here once and for all.

image

Casting from a Circle or Rectangle to a Shape is upcasting, casting up in the hierarchy.

Casting from a Shape object to a Circle object is downcasting, casting down in the hierarchy. If you find yourself downcasting, it may be an indication of a code smell, think twice about it!

Changed name and moved

No, I didn’t join the witness protection program or anything like that, it’s not my name that changed, and I didn’t move. However I did change the name of the mock-/stub-/fake-framework Legend.Fakes to the – in my opinion – catchier FakeItEasy and I also moved the source to from CodePlex to Google code since the svn support is way better there.

The new location of the source is: http://code.google.com/p/fakeiteasy/

Friday, August 7, 2009

Fake wrappers (candy inside)

I added a new feature to FakeItEasy the other day, it lets you put a fake wrapper around a real instance. This means that all calls that are not explicitly configured to do anything different are delegated to the wrapped instance, this gives you the ability to fake out only a certain method on a fake.

For example, you might have a web service of some sort:

public interface IStoreService
{
    IEnumerable<IProduct> FindAllProducts();
    int BuyProduct(IProduct product);
}

public interface IProduct
{
    string ProductId { get; }
    decimal Price { get; }
}

Let’s say in an integration test of a class we are writing called PersonalShopper you want to run against an actual (let’s event say a sealed) implementation of this service, we can call it RidiculouslyOverPricedStore, but you want to fake out the BuyProduct-method so that nothing is actually booked in the remote system.

Here’s the PersonalShopper class we want to write an integration test for:

public class PersonalShopper
{
    private IStoreService store;

    public PersonalShopper(IStoreService store)
    {
        this.store = store;
    }

    public IProduct BuyMeSomething()
    {
        var productToBy =
            (from product in this.store.FindAllProducts()
             orderby product.Price
             select product).First();

        this.store.BuyProduct(productToBy);
    }
}

Here’s a test for this where we create a fake wrapping an instance of the RidiculouslyOverPricedStore-class, we then configure calls to the BuyProduct-method with any product to return 1 (this is meant to be the order id).

[Test]
public void Personal_shopper_buys_a_product()
{
    // Arrange
    var realStore = new RidiculouslyOverPricedStore();
    var fakedStore = A.Fake<IStoreService>(x => x.Wrapping(realStore));

    A.CallTo(() => fakedStore.BuyProduct(A<IProduct>.Ignored.Argument)).Returns(1);

    var shopper = new PersonalShopper(fakedStore);

    // Act
    var boughtProduct = shopper.BuyMeSomething();

    // Assert
    Assert.That(boughtProduct, Is.Not.Null);
}

Another case to use this feature is if you have a class that you want to use in your test that you don’t have to configure at all, but you still want to assert that a certain method was called, just wrap an instance, use it as normal without configuring it and use Fake.Assert to assert on it.

Friday, July 31, 2009

Event raising syntax

Syntax for event raising is kind of awkward across the line, and for good reason, there simply is no really good way of doing it since an event always has to be positioned to the of an event attachment or detachment (+= or –=).

Just from the top of my head I think the way it’s done (or rather one of the ways you can do it) in Rhino Mocks is something like this:

var foo = MockRepository.GenerateMock<IFoo>();
foo.Raise(x => x.SomethingHappened += null, foo, EventArgs.Empty);

I think (I have not implemented this yet so I’m not sure it works) that I just came up with a rather different and maybe simpler way of doing it for Legend.Fakes. If it’s simpler or not I’ll leave up to you, but there’s a definite benefit in that it’s type safe on the event argument:

var foo = A.Fake<IFoo>();

// with sender explicitly:
foo.SomethingHappened += Raise.With(foo, EventArgs.Empty).Now;

// with the fake object as sender:
foo.SomethingHappened += Raise.With(EventArgs.Empty).Now;

Thursday, July 30, 2009

Released Legend.Fakes on CodePlex

http://fakes.codeplex.com/

It has moved to FakeItEasy.

Read more: http://ondevelopment.blogspot.com/2009/08/changed-name-and-moved.html

Legend.Fakes configuration fluent interface

As I mentioned in my earlier post one of the things I want to avoid in my mock-/stub-/fake-framework is extension methods that clutter intellisense, this means that you have to get a configuration object to be able to start configuring your fake, don’t be afraid though, it’s really easy and there are two ways to do it. The first is to call the static method “Fake.Configure(object fakedObject)” with the fake object you want to configure, but you can also import the namespace “Legend.Fakes.ExtensionSyntax” and now you can call the “Configure” extension method directly on your faked object. If you do the latter you will have ONE extension method cluttering intellisense, but I can live with just one. Once you have the configuration object you have a fluent interface API.

IPerson person = A.Fake<IPerson>();

// Static method...
Fake.Configure(person);

// Once Legend.Fakes.ExtensionSyntax is imported you can use...
person.Configure();

 

When you have created a fake, the interface of the fake is a lot more discoverable since intellisense shows you what interface it provides: nonCluttered

The fluent interface is context aware so subsequent calls will only have certain options available depending on the call before. For example you can only specify a return value if the call you’re configuring is not a void call:

functionCall

A void call would look like this:

voidCall

Here’s some example configuration code:

var file = A.Fake<IFile>();

file.Configure()
    .CallsTo(x => x.Delete())
    .Throws(new NotSupportedException("You're not allowed to delete a file."))
    .Once();

file.Configure()
    .CallsTo(x => x.GetFileSizeInBytes()).Returns(400);

file.Name = "c:\filename.txt";

Wednesday, July 29, 2009

Introducing Legend.Fakes

OK, you’ll think I’ve lost it – or maybe you never thought I had it – but I’m creating my own mocking framework.

Why? Well, first of all because I wanted a framework that is more semantically correct and easier to understand so instead of distinguishing between mocks and stubs it just produces “fakes”, if a fake is a mock or a stub depends on the use of it. I also wanted a simpler and cleaner syntax for configuration, I’m really not a fan of the many extension methods cluttering Intellisense in your tests when using Rhino Mocks (although I really love Rhino Mocks).

clutternedIntellisense

I also thought it would be a really nice learning experience. Finally there are a few features I think will be cool that I will include that no other framework has (to my knowledge, though I’m only really familiar with Rhino).

But the main feature is and should be ease of use, so, to create a fake object (whether it’s a mock or a stub) you’d write this:

IFoo foo = A.Fake<IFoo>();

I’ll write more about other features, my learning experience while implementing this and post code soon.

Sunday, July 5, 2009

Round and round (my head spins)

A year or so ago I ran into a piece of code that made me a little dizzy and nauseous. I've created a piece of code similar to the code in question but the original code was in VB so I can't truly reproduce it but this will have to suffice. Can you figure out what the code does (line 7 in particular)?

public class Foo
{
    private string scoreLabelText;

    public Foo(decimal score)
    {
        score = (Convert.ToInt32((score * 10) / 5) * 5) / 10m;
        this.scoreLabelText = score.ToString();
    }
}

I figured it did pretty much nothing and thought that it had gotten in there by mistake or because some code had changed around it and that it had been significant in the past but wasn’t any more. Normally I would just have deleted it but I was lucky in that I could run a svn-blame and see who wrote it. So I called him and said something like “you’re never gonna be able to talk your way out of this one!”. The thing was, he could, since the code actually does something, it’s just that it’s totally non obvious. What it does is that it rounds the value to the nearest multiple of 0.5. For example…

  • 14.234 = 14
  • 14.44 = 14.5
  • 93.1 = 93
  • 93.71 = 93.5

What brought me to writing this blog post was that a guy new to the project ran into this same piece of code this Friday and had the same initial reaction as I did, he wanted to delete the line. That the "algorithm” is actually buggy is beside the point, the point is that code should always express it’s intent. The following would be a lot easier to understand:

public class Foo
{
    private string scoreLabelText;

    public Foo(decimal score)
    {
        var roundedScore = RoundToNearestHalfOrIntegerValue(score);
        this.scoreLabelText = roundedScore.ToString();
    }

    private static decimal RoundToNearestHalfOrIntegerValue(decimal value)
    {
        return (Convert.ToInt32((value * 10) / 5) * 5) / 10m;
    }
}

So just by moving the hard to decipher line into a method of its own we’ve made it a lot easier to understand and it’s also a lot less likely to be changed by someone who doesn't understand what the code should do.

As I said earlier there’s also a bug in the code. The bug is that it will round half way values down sometimes, for example 1.25 will be rounded to 1 instead of 1.5. I consider this a bug in this case since it’s not what’s intended even though it’s not necessarily an invalid way of doing rounding (it’s almost bankers rounding). A more to the point algorithm solves this problem and actually is a little more readable to. Note that this is not the only algorithm I could’ve chosen for this task, it’s just that it’s the one that I think is the most readable in the specific context.

public class Foo
{
    private string scoreLabelText;

    public Foo(decimal score)
    {
        var roundedScore = RoundToNearestHalfOrIntegerValue(score);
        this.scoreLabelText = roundedScore.ToString();
    }

    private static decimal RoundToNearestHalfOrIntegerValue(decimal value)
    {
        return Math.Round(value * 2m) / 2m;
    }
}

Thursday, May 21, 2009

NUnit ValuesAttribute is tasty delicious!

There are quite a few nice features in the new 2.5 release of NUnit so if you’ve not yet checked it out please do so. I’ve migrated to it in all our solutions at work and we’ve had no problems, we did have to upgrade to the latest versions for TestDriven.Net and TeamCity, but hey, upgrading is a good thing.

One thing I really like is the ValuesAttribute, if you’ve done parameterized tests (that were previously available in the NUnit.Framework.Extensions library) this is something similar. Just tag your test as a normal Test-method but add a parameter and tag that parameter with the ValuesAttribute like this:

[TestFixture]
public class ValidatorTests
{
    [Test]
    public void IsInRange_returns_true_for_values_that_are_in_range([Values(1,2,3)] int value)
    {
        var validator = new Validator();
        validator.IsInRange(value, 1, 3);
    }
}

public class Validator
{
    public bool IsInRange(int value, int lowerBound, int upperBound)
    {
        return value >= lowerBound && value <= upperBound;
    }
}

This will result in three tests being run, one for each value, quite nice.

The really cool thing is that you can add more than one parameter each tagged with this attribute and the number of tests will be the cross-product of the values.

Sunday, May 17, 2009

Cast null values in tests

My first tests of classes are often tests that asserts that the constructor throws ArgumentNullException for null arguments, something like this:

[Test]
public void constructor_throws_when_fileSystem_is_null()
{
    Assert.Throws<ArgumentNullException>(() =>
        {
            new TransactionalFileSystem((IFileSystem)null, this.transactionManager);
        });
}

As you see I explicitly cast the null value to the type of the parameter in the constructor signature, this is benefitial for two reasons:

  1. It reads better, the reader know what it is that is NOT passed in.
  2. Several times in the past I have refactored and reordered the parameters in the constructor with the result that the tests test the wrong parameters this is avoided this way.

Tuesday, April 21, 2009

Open source

I’ve decided to open source most of my personal libraries (not those specific to clients obviously). Find them at CodePlex.

Synchronization and unit testing

There are a number of different ways to synchronize access to resources in .net, the most common ones are probably the Monitor class (used by the lock-keyword) and the ReaderWriterLock (or ReaderWriterLockSlim) classes, others are semaphores and mutex’s. When using TDD to develop you want to be able to test that your code is actually locking the resources it should but you don’t want to rely on spinning off threads to check if resources are locked or not in your unit tests (because it would actually make them not unit tests  but rather integration tests).What I’ve done is to create an interface that is called ISynchronizationManager and the public members of this interface I’ve actually more or less stolen from the ReaderWriterLockSlim class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Legend.Threading
{
    /// <summary>
    /// Represents a manager that synchronizes
    /// access to a resource.
    /// </summary>
    public interface ISynchronizationManager
        : IDisposable 
    {
        /// <summary>
        /// Enters the read lock.
        /// </summary>
        void EnterReadLock();

        /// <summary>
        /// Exits the read lock.
        /// </summary>
        void ExitReadLock();

        /// <summary>
        /// Enters a synchonization managed section in
        /// write mode.
        /// </summary>
        void EnterWriteLock();

        /// <summary>
        /// Exits the write lock.
        /// </summary>
        void ExitWriteLock();

        /// <summary>
        /// Enters an upgradable read lock.
        /// </summary>
        void EnterUpgradableReadLock();

        /// <summary>
        /// Exits an upgradable read lock.
        /// </summary>
        void ExitUpgradableReadLock();

        /// <summary>
        /// Gets the recursion policy set on the lock.
        /// </summary>
        LockRecursionPolicy RecursionPolicy { get; }
    }
}

This lets me write unit tests that tests the interaction with this interface that I can easily mock with a mocking framework of choice (that’s Rhino Mocks to me). An example of how a test  in NUnit could look:

[Test]
public void should_acquire_write_lock_on_timerSynchronizationManager()
{
    scheduler.Schedule(voidAction, currentTime.AddMinutes(1));
    currentTime = currentTime.AddMinutes(1);

    timer.Raise(x => x.Elapsed += null, timer, EventArgs.Empty);

    synchronizationManager.AssertWasCalled(x => x.EnterWriteLock(), x => x.Repeat.Twice());
}

For production I have a couple of different implementations of this interface internally using monitors, ReaderWriterLockSlim and other ways of synchronizing. What’s nice it that I can inject the ISynchronizationManager as a dependency in the constructor of a class that needs to be synchronized and use an IoC container to register the synchronization manager to use.

I also created some extension methods for the ISynchronizationManager that lets you lock on it like this:

ISynchronizationManager manager = GetSynchronizationManager();
using (manager.AcquireReadLock())
{ 
    // read something from your shared resource...
}

To see this in action check out the Legend.Threading.Scheduler-class and the tests of it in the Legend project.

Thursday, April 2, 2009

Unleashing modules – part 2

This is a continuation to the post that I did a couple of days ago about loading AutoFac-modules with the help of MEF (Managed Extensibility Framework). In this post I’ll show and discuss my implementation.

The implementation

If I have an assembly that has an AutoFac module that sets up the dependencies for that assembly I would like to “export” this module through the magic of MEF. Rather than exporting the modules themselves I chose to export a delegate type that I’ve named ModuleFactory. The signature is as follows:

using Autofac;

namespace Legend.Autofac
{
    /// <summary>
    /// Creates an <see cref="IModule" /> that's responsible for loading
    /// dependencies in the specified context.
    /// </summary>
    /// <param name="mode">The mode the application is running in, let's the implementor
    /// of the factory load different dependenices for different modes.</param>
    /// <returns>An <see cref="IModule" />.</returns>
    public delegate IModule ModuleFactory(ApplicationMode mode);
}

 

As you see this factory delegate type takes an argument called “mode” of the type ApplicationMode, this is an enum of different modes an application can be run in (test, staging and production) and gives the factory a chance to load different dependency configuration depending on the mode of the application. For example, if a library communicates with a web-service, in test mode you might want to use a fake version of this web-service. As you will see later this mode is set on the ComposedModule and it’s the module that passes it to the factories. I’ve been going back and forward on this one, thinking that I might want to use a string instead of an enum so that it’s the set of options is not closed but I’m leaning towards the enum-solution. This is the definition of the enum:

namespace Legend.Autofac
{
    /// <summary>
    /// Describes different modes an application can run in.
    /// </summary>
    public enum ApplicationMode
    {
        /// <summary>
        /// The application is running in a test environment.
        /// </summary>
        Test = 0,
        
        /// <summary>
        /// The application is running in a staging environment.
        /// </summary>
        Staging = 1,

        /// <summary>
        /// The application is running in production environment.
        /// </summary>
        Production = 2
    }
}

So, last but not least, the ComposedModule itself. As I mentioned earlier, the module takes in a ComposablePartCatalog in it’s constructor and uses this catalog to load all the exported ModuleFactories. I also provide an overload of the constructor that takes a string that’s a path to a directory containing dll’s that contains your exports, a MEF DirectoryCatalog will be created for this directory. The constructor also takes in the ApplicationMode that will be passed to the ModuleFactories.

using Autofac.Builder;
using Autofac;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Collections.Generic;
using System;

namespace Legend.Autofac
{
    /// <summary>
    /// An <see cref="Autofac.Builder.Module" /> is composed by with the help of
    /// the System.ComponentModel.Composition (MEF) framework.
    /// </summary>
    public class ComposedModule
        : global::Autofac.Builder.Module
    {
        #region Fields
        private ApplicationMode mode;
        private ComposablePartCatalog catalog;
        [Import(typeof(ModuleFactory))]
        private IEnumerable<ModuleFactory> RegisteredModuleFactories; 
        #endregion

        #region Construction
        /// <summary>
        /// Creates a new ComposedModule using the specified catalog to
        /// import ModuleFactory-instances.
        /// </summary>
        /// <param name="mode">The mode the application is running in.</param>
        /// <param name="catalog">The catalog used to import ModuleFactory-instances.</param>
        public ComposedModule(ApplicationMode mode, ComposablePartCatalog catalog)
        {
            if (catalog == null) throw new ArgumentNullException("catalog");

            this.mode = mode;
            this.catalog = catalog;

            this.ImportFactories();
        }

        /// <summary>
        /// Creates a new ComposedModule that loads all the ModuleFactories
        /// exported in assemblies that exists in the directory specified in 
        /// the <param name="modulesDirectoryPath" />-parameter.
        /// </summary>
        /// <param name="mode">The mode the application is running in.</param>
        /// <param name="catalog">The catalog used to import ModuleFactory-instances.</param>
        public ComposedModule(ApplicationMode mode, string modulesDirectoryPath)
            : this(mode, new DirectoryCatalog(modulesDirectoryPath)) { } 
        #endregion

        #region Methods
        private void ImportFactories()
        {
            var batch = new CompositionBatch();
            batch.AddPart(this);

            var container = new CompositionContainer(this.catalog);
            container.Compose(batch);
        }

        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            foreach (var factory in this.RegisteredModuleFactories)
            {
                var module = factory(this.mode);
                builder.RegisterModule(module);
            }
        } 
        #endregion
    }
}

 

Using it

All you have to do to use it is to create modules and export ModuleFactory methods like this:

public class FooModule
    : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        base.Load(builder);

        builder
            .Register(x => new Foo())
            .As<IFoo>()
            .FactoryScoped();
    }

    [Export(typeof(ModuleFactory))]
    public static ModuleFactory Factory = x => new FooModule();
}

 

That’s all you need, and then of course register the ComposedModule in you container!

If you have any comments, suggestions, questions or so, please don’t hesitate to comment here or catch me over at Twitter: @patrik_hagne.

I’m going to publish the source in some place better soon, but for now grab it here.

Monday, March 30, 2009

Unleashing modules

I’m a big fan of the Autofac IoC-container, it’s pretty light weight, blazingly fast and very object oriented. One of the features I love the most is the ability to divide the boot strapping code into modules. Also, to set up your dependencies in code with a fluent interface rather than in an xml-file is great in so many ways (intellisense and refactoring to name a few). The one problem I’ve found with this is that it couples your assemblies tighter than they might need to be coupled.

The problem

Let’s consider this example: We have an application that makes use of the service IFoo, this interface is defined in the assembly FooAssembly. There is an implementation of the IFoo-interface called XmlFoo in the XmlFooAssembly and this implementation is the implementation we want to use in our application. The implementer of the XmlFooAssembly has been nice enough to provide a module that registers the XmlFoo as an IFoo and also registers services that the XmlFoo-implementation itself is dependent upon. This is quite nice since now, in our boot strapping code what we have to do is to register that module along with any other registrations we have, something like this:

var builder = new ContainerBuilder();

builder.RegisterModule(new MyApplicationDependencyModule());
builder.RegisterModule(new XmlFooDependencyModule());

var container = builder.Build();

 

This is all pretty nice and clean, not much of a problem right? Well, there is one problem with this, in order for us to register the XmlFooDependencyModule we have to have a reference to the assembly where it’s defined (XmlFooAssembly) from our application assembly, note that this is the only place we need this reference, in all other places we’re programming against the abstraction IFoo, not the XmlFoo. This couples the assemblies more tightly than they need to be. It’s not that this is a giant problem, and it can be solved by using xml-configuration of dependencies rather than using the module directly, however, another problem with this is that if we’re using the same dependencies in multiple applications we have a lot of boiler plate code in that is duplicated along applications.

Your going to fix this are you?

Well, yeah, there is a point with this blog post. I guess you’re familiar with MEF (Managed Extensibility Framework), if not go read up on it, it’s a very cool technology. My idea is that we could use MEF to export the modules from the assemblies that implement them and import them in the application that uses them, this way we can remove the reference to the XmlFooAssembly. Instead of registering the modules we know exists, we register all modules that are “magically” imported. To do this I created a new module type that inherits the Autofac.Builder.Module-class and is called ComposedModule. You can for example instantiate the module with a path to a directory that contains a number of assemblies, the composed module will then (through MEF) find all the exported modules in the assemblies in the folder. When you register this composed module in your builder it will register all the imported modules in the builder:

var builder = new ContainerBuilder();

builder.RegisterModule(new ComposedModule(@"c:\MyApplicationDirectory"));

var container = builder.Build();

 

You could actually give the ComposedModule a MEF-catalog instead of the directory path and the ComposedModule will use this catalog to load the exported modules:

var builder = new ContainerBuilder();

builder.RegisterModule(new ComposedModule(new AssemblyCatalog(this.GetType().Assembly)));

var container = builder.Build();

A blog post about the implementation details and some other features of the ComposedModule is coming in the next few days so please check back for that.

Sunday, March 8, 2009

If If Then Throw New CodeSmellException()

I’ve had this – somewhat controversial – opinion for a long time, that if you have an if-statement there’s something wrong with your design. Of course this is taking it a bit too far, but I think that the initial reaction for any developer that finds her-/himself writing an if-statement should be “could I do this differently”.

The last week I’ve been leading a new team and we’re starting a new project and we’ve been building a prototype for the product we’re going to build. It’s an API intended for internal use and I can’t talk to much about it but it’s not a trivial piece of software. It handles going out to external systems, aggregating answers from them, displaying the information in a UI and let’s the user communicate back to the external systems with additional information. The prototype has maybe something like twenty classes and a couple of hundred lines of code, now here’s the point of this whole post: this Thursday when at least 90% of that code was already written we wrote our first if-statement. I called it out “there it is!”. The other developers were like: “what?”. “-That’s our first if-statement”. The prototype is done and there is still one single if-statement in it, and it’s not that we’ve been trying to avoid it, we’ve just designed with the SOLID-principles in mind which leads to a more sound and less complex architecture.

Thursday, February 26, 2009

Fluent interface for argument validation

I was fiddling around a bit with a fluent interface for validating method-arguments, it looks kind of promising…

    Public Class Foo
        Public Sub New(ByVal bar As String, ByVal baz As Integer)
            Ensure.ThatArgument(bar).IsNotNull()
            Ensure.ThatArgument(baz).IsInRange(1, 10)

            ' The argument can be named to for better exception messages...
            Ensure.ThatArgument(bar).Named("bar").IsNotNull()
            Ensure.ThatArgument(baz).Named("baz").IsInRange(1, 10)
        End Sub
    End Class

Using generics also makes the intellisense really helpful, for example the “IsInRange”-validation only shows up for IComparable(T)-types.

Thursday, February 12, 2009

String concatenation made easy

How many times have you written code similar to this?

   1: var builder = new StringBuilder();
   2:  
   3: foreach (string foo in bar)
   4: {
   5:     builder.Append(foo);    
   6: }
   7:  
   8: return builder.ToString();

I have hopefully done it for the last time since I created a couple of extension methods for IEnumerable<string>, well actually, one method with a couple of overloads.

The first one is really simple and just concatenates all the strings in the specified collection to a single string, something like:

   1: var sequence = new string[] { "foo", "bar" };
   2: string result = sequence.Concatenate();

In this case the result variable will contain the string “foobar”. One of the overloads will let you specify a separator:

   1: var sequence = new string[] { "foo", "bar" };
   2: string result = sequence.Concatenate(", ");

Now the result is “foo, bar”.

And the last one will let you specify a prefix and a suffix in addition to the separator:

   1: var sequence = new string[] { "foo", "bar" };
   2: string result = sequence.Concatenate(", ", "(", ")");

Giving you the result “(foo, bar)”. Quite neat!

Here’s the code for the extensions:

   1: /// <summary>
   2: /// Concatenates all the strings in the specified sequence.
   3: /// </summary>
   4: /// <param name="values">The values to concatenate.</param>
   5: /// <returns>The concatenated sequence.</returns>
   6: public static string Concatenate(this IEnumerable<string> values)
   7: {
   8:     return values.Concatenate(string.Empty);
   9: }
  10:  
  11: /// <summary>
  12: /// Concatenates all the strings in the specified sequence, separated by
  13: /// the specified separator.
  14: /// </summary>
  15: /// <param name="values">The values to concatenate.</param>
  16: /// <param name="separator">A string that will be inserted between all the values
  17: /// in the resulting string.</param>
  18: /// <returns>The concatenated sequence, separated by
  19: /// the specified separator.</returns>
  20: public static string Concatenate(this IEnumerable<string> values, string separator)
  21: {
  22:     return values.Concatenate(separator, string.Empty, string.Empty);
  23: }
  24:  
  25: /// <summary>
  26: /// Concatenates all the strings in the specified sequence, separated by
  27: /// the specified separator, prefixed by the value specified in <paramref name="prefix" /> and
  28: /// suffixed by the value specified in <paramref name="suffix"/>.
  29: /// </summary>
  30: /// <param name="values">The values to concatenate.</param>
  31: /// <param name="separator">A string that will be inserted between all the values
  32: /// in the resulting string.</param>
  33: /// <param name="prefix">A string that will be the start of the result string.</param>
  34: /// <param name="suffix">A string that will be the end of the result string.</param>
  35: /// <returns>The concatenated sequence, separated by
  36: /// the specified separator, prefixed by the value specified in <paramref name="prefix" /> and
  37: /// suffixed by the value specified in <paramref name="suffix"/>.</returns>
  38: public static string Concatenate(this IEnumerable<string> values, string separator, string prefix, string suffix)
  39: {
  40:     Guard.ArgumentNullException(values, "values");
  41:     Guard.ArgumentNullException(separator, "separator");
  42:     Guard.ArgumentNullException(prefix, "prefix");
  43:     Guard.ArgumentNullException(suffix, "suffix");
  44:  
  45:     var result = new StringBuilder();
  46:  
  47:     result.Append(prefix);
  48:  
  49:     foreach (var value in values)
  50:     {
  51:         if (result.Length > prefix.Length)
  52:         {
  53:             result.Append(separator);
  54:         }
  55:  
  56:         result.Append(value);
  57:     }
  58:  
  59:     result.Append(suffix);
  60:  
  61:     return result.ToString();
  62: }

… and some NUnit-tests:

   1: [TestFixture]
   2: public class sequence_of_strings_Concatenate
   3: {
   4:     string[] sequence;
   5:  
   6:     [SetUp]
   7:     public void SetUp()
   8:     {
   9:         this.OnSetUp();
  10:     }
  11:  
  12:     protected virtual void OnSetUp()
  13:     {
  14:         sequence = new string[] { "a", "b", "c" };
  15:     }
  16:  
  17:     [Test, ExpectedException(typeof(ArgumentNullException))]
  18:     public void should_throw_exception_when_sequence_is_null()
  19:     {
  20:         Legend.Collections.Collection.Concatenate(null);
  21:     }
  22:  
  23:     [Test]
  24:     public void should_concatenate_values()
  25:     {
  26:         var result = sequence.Concatenate();
  27:         Assert.AreEqual(result, "abc");
  28:     }
  29: }
  30:  
  31: [TestFixture]
  32: public class sequence_of_strings_Concatenate_with_specified_separator
  33: {
  34:     string[] sequence;
  35:  
  36:     [SetUp]
  37:     public void SetUp()
  38:     {
  39:         this.OnSetUp();
  40:     }
  41:  
  42:     protected virtual void OnSetUp()
  43:     {
  44:         sequence = new string[] { "a", "b", "c" };
  45:     }
  46:  
  47:     [Test, ExpectedException(typeof(ArgumentNullException))]
  48:     public void should_throw_exception_when_sequence_is_null()
  49:     {
  50:         Legend.Collections.Collection.Concatenate(null, ",");
  51:     }
  52:  
  53:     [Test, ExpectedException(typeof(ArgumentNullException))]
  54:     public void should_throw_exception_when_separator_is_null()
  55:     {
  56:         sequence.Concatenate(null);
  57:     }
  58:  
  59:     [Test]
  60:     public void should_concatenate_values_separated_by_separator()
  61:     {
  62:         var result = sequence.Concatenate(", ");
  63:         Assert.AreEqual(result, "a, b, c");
  64:     }
  65: }
  66:  
  67: [TestFixture]
  68: public class sequence_of_strings_Concatenate_with_specified_separator_prefix_and_suffix
  69: {
  70:     string[] sequence;
  71:  
  72:     [SetUp]
  73:     public void SetUp()
  74:     {
  75:         this.OnSetUp();
  76:     }
  77:  
  78:     protected virtual void OnSetUp()
  79:     {
  80:         sequence = new string[] { "a", "b", "c" };
  81:     }
  82:  
  83:     [Test, ExpectedException(typeof(ArgumentNullException))]
  84:     public void should_throw_exception_when_sequence_is_null()
  85:     {
  86:         Legend.Collections.Collection.Concatenate(null, ",", string.Empty, string.Empty);
  87:     }
  88:  
  89:     [Test, ExpectedException(typeof(ArgumentNullException))]
  90:     public void should_throw_exception_when_separator_is_null()
  91:     {
  92:         sequence.Concatenate(null, string.Empty, string.Empty);
  93:     }
  94:  
  95:     [Test, ExpectedException(typeof(ArgumentNullException))]
  96:     public void should_throw_exception_when_prefix_is_null()
  97:     {
  98:         sequence.Concatenate(string.Empty, null, string.Empty);
  99:     }
 100:  
 101:     [Test, ExpectedException(typeof(ArgumentNullException))]
 102:     public void should_throw_exception_when_suffix_is_null()
 103:     {
 104:         sequence.Concatenate(string.Empty, string.Empty, null);
 105:     }
 106:  
 107:     [Test]
 108:     public void should_concatenate_string_with_separator_prefix_and_suffix_appended()
 109:     {
 110:         var result = sequence.Concatenate(", ", "(", ")");
 111:         Assert.AreEqual("(a, b, c)", result);
 112:     }
 113: }