Mock object of death

Following on from my NullOf<T> class, I decided to write something that enables me to throw an exception from any method on an interface.  That meant I could easily write unit tests to check exception handling.  It does a similar job to the “null implementation” of an interface, but allows you to specify that a certain method will raise an exception.  This is what I’ve got:

using System;
using System.Linq.Expressions;
using Moq;

namespace
MyNamespace
{
    public class OfDeath<T> where T: class
    {
        public static T ErrorsWhen(Expression<Action<T>> someAction)
        {
            return ErrorsWhen(someAction, new Exception("It's all gone horribly wrong!"));
        } 

        public static T ErrorsWhen(Expression<Action<T>> someAction, Exception ex)

        {

            Mock<T> mocker = new Mock<T>(MockBehavior.Loose);

            mocker.Setup(someAction).Throws(ex);

            return mocker.Object;

        }

    }
}

You’ll see that there are two overloads; one allows you to specify whatever exception you like (the other makes an exception for you).  Usage looks like this:

 

MyService service = new MyService(OfDeath<ILog>.ErrorsWhen(x => x.Info(It.IsAny<object>())));

service.DoSomething();


So this example throws an exception when you call ILog.Info(), but not when you call any of the other methods on the ILog interface.  Again, it’s generic, so you can point it at other interfaces and make them throw exceptions too.

 

Mocking null implementations of Interfaces

People who know me understand that I like pretty code.  This post describes something that I came up with to make my units tests look more pretty.  Say you want to run a unit test on a service, and normally that service would log lots of stuff (using log4net for example).  But for the purpose of the unit test you just want to throw away all the log entries.  You might use moq, and do something like this:

log4net.ILog logToNull = new Mock<ILog>(MockBehavior.Loose).Object;
var service = new MyService(logToNull);
service.DoSomething();

...which is all very fine; but not especially pretty.  I decided to make it look a little better -  what if we add this class to our project:

using Moq; 

namespace MyNamespace

{

    public class NullOf<T> where T: class

    {

        public static readonly T Instance = new Mock<T>(MockBehavior.Loose).Object;

    }

}

It’s not very complicated, but means that now we can do this:

 

var service = new MyService(NullOf<log4net.ILog>.Instance);

service.DoSomething();

Ahh, we still have a “null” implementation of the ILog interface, but to me saying “NullOf<log4net.ILog>.Instance“ looks just a bit nicer :-) Better than that, it’s generic, so you can use it on other interfaces too.  Null implementations all round then.