Friday, May 1, 2015

Alternative to mocking static methods in C#

Curious what you guys think of this as an alternative to mocking static methods in C#?
Here's a a simply way to mock static methods without a mocking framework.

Say you have code like this:
        class Math
        {
            public static int Add(int x, int y)
            {
                return x + y;
            }

You want to "mock" the Add method, but you can't. Change the above code to this:

        class Math
        {
            public static Func Add = (x, y) =>
            {
                return x + y;
            };

Existing client code doesn't have to change (maybe recompile), but source stays the same.

Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:
    [TestMethod]
    public static void MyTest()
    {
        Math.Add = (x, y) =>
        {
            return 11;
        };dada

Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.

This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.

Another thing to keep in mind.   When you set the static variable like that, you should undo it when the test is complete.   One way to do that is to re-run the class's static initializer. 

 Example:
    typeof(SomeClassName).TypeInitializer.Invoke(null, null);