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.

 

A new lock statement for C#

I'm working on a lot of multithreaded code at the moment.  In the past I have made use of the lock keyword in C#, but I'm not doing that anymore because it is much better to have a timeout.  However, I don't like having lots of sections like this in my code:

 

if (System.Threading.Monitor.TryEnter(objLock, TIMEOUT))

{

    try

    {

        // do stuff here...

    }

    finally

    {

        System.Threading.Monitor.Exit(objLock);

    }

}

 

...which is the equivalent of using the lock statement, but with a timeout specified.  Still, what I'd like to see in my code is something like this:

 

lock (objLock,TIMEOUT)

{

    // do stuff here...

}

 

Which would be more pretty.  And since I like pretty code, I decided to see how close I could get to that.  This is my current solution:

 

public static class Lock

{

    public static T Try<T>(object objLock, int timeout, Func<T> f)

    {

        if (System.Threading.Monitor.TryEnter(objLock, timeout))

        {

            try

            {

                return f.Invoke();

            }

            finally

            {

                System.Threading.Monitor.Exit(objLock);

            }

        }

        return default(T);

    }

 

    public static void Try(object objLock, int timeout, Action f)

    {

        if (System.Threading.Monitor.TryEnter(objLock, timeout))

        {

            try

            {

                f.Invoke();

            }

            finally

            {

                System.Threading.Monitor.Exit(objLock);

            }

        }

    }

}

 

So far, that is as close as I can get, it means that I can do two things:

 

Lock.Try(objLock, TIMEOUT, delegate

{

    // stuff here...

});

 

or, if I need to return a value, then this:

 

return Lock.Try<int>(objLock,TIMEOUT,delegate

{

    // stuff here...

    return 0;

});

 

Because the second example uses generics, then I can return anything I like by specifying the type inside the angled brackets.  Now I feel that my code is a lot more prettier which is a nice way to finish off on a Friday.

Opening WPF Windows on a new thread

Recently I needed to open a new WPF window on a new thread. I was helped a great deal by this article, however the window that I needed to open did not have parameterless constructor.  In the end, this is the code that I came up with:

private void NewWindowThread<T,P>(Func<P, T> constructor, P param) where T : Window

{

   Thread thread = new Thread(() =>

   {

      T w = constructor(param);

      w.Show();

      w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();

      System.Windows.Threading.Dispatcher.Run();

   });

   thread.SetApartmentState(ApartmentState.STA);

   thread.Start();

}

This method, uses generics to specify the Type of the window that you're creating as well as the Type of the parameter passed to its constructor, for example:

string t = "Hello World!";

NewWindowThread<TitleWindow, string>(c => new TitleWindow(c), t);

Would work when TitleWindow was declared like this:

public class TitleWindow : Window

{

    public TitleWindow(string title)

    {

        this.Title = title;

    }

}

Now I can open different types of window on a new thread and pass parameters to them.