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.