Static Mocking with JustMock

One of the coolest (and scariest) things I’ve seen lately is mocking static classes and methods with JustMock. I was working on some legacy code, and was making some changes, so I wanted to make sure that I got everything tested first. When I went to write the tests, I noticed that I needed to wrap and hide away a static method that was being called.

My eventual intent, however, is to get rid of the static class and method calls if possible. Writing the wrapper around it temporarily, so I can get tests in place before refactoring has always seemed like a pain. I went to check and see if JustMock would be able to mock a static class. That seemed like one of those crazy things that commercial mocking frameworks can usually do. I was right. It could mock the static class. (SCARY!!)

I wrote some code that looked like this: (Sorry I can’t show you my clients’ code in my blog without their permission, so you get sample code.)

public static class MyStaticClass
{
    public static int DoSomeDependentStuffThatIsHardToFix()
    {
        // Pretend this does more than just returning 1
        return 1;
    }
}

 

In my example, I need to test some code calling this static method. Normally, I would put a wrapper around this class, write my tests, refactor, and eventually change this to not be a static dependency anymore.

I decided to try this. Here is a test class that uses mocking to demonstrate how I can decide any result for this method and have control of this dependency. Notice that my method always returns 1. Pretend that a different result were possible.

Now when I go to write my test, I can just Mock out the static and define that I want that method to be called and for it to return 2 instead of 1. I will then assert that it worked as I expected in my test. Once I confirm that the mock works as expected using this type of test, I can put it in place in my actual test. (Yes, I sometimes write temporary tests to confirm what I expect before I write the whole test. Little steps.)

[TestFixture]
public class MyTestClass
{
    [Test]
    public void WhatIsTestedDoesNotMatter()
    {
        Mock.SetupStatic(typeof(MyStaticClass));
 
        Mock.Arrange(() => MyStaticClass.DoSomeDependentStuffThatIsHardToFix()).Returns(2);
 
        Assert.AreEqual(2, MyStaticClass.DoSomeDependentStuffThatIsHardToFix());
    }
}

Then when I go and run my tests, I get this nice result showing me that everything is working as I expect it to. Yippee!

JustMock Static Test Passing

How it achieves this? I am not sure. I intend to find out though. When I do, I will write a post explaining it.

Have a good day!

Comments