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.