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.