Mocking Static Extension Methods for Unit Testing
Mocking is an essential component to any good unit testing strategy. It allows us to replace the concrete implementation of a class with a test version whose behavior you control. When designing a system from scratch, we can use dependency inversion to make sure everything is mockable. However, when working with an existing system, there may be hidden dependencies that require some creative thinking.
I recently came across a situation where I needed to unit test some code that had dependencies on Microsoft's OWIN extension methods. The methods in question belonged to the static class OwinContextExtensions.
I was using Moq as my mocking framework, which doesn't provide a mechanism for mocking static extension methods.
To overcome this hurdle, I created a wrapper class which exposed the same methods, but as instance methods. I then extracted an interface from my new wrapper class, so that I could mock it up. Here is the new interface for the wrapper class. Notice that it has the same methods as the original extension class, but as regular methods.
Finally, here's the wrapper class itself. As you can see, it still makes use of the original extension methods. However, this implementation is abstracted from the user, in this case the unit test.
To bring it all together, once the wrapper class and interface were in place, it was time to wire everything up. First I had to create a number of mocks on which there were dependencies. In this case, the wrapper is provided to the controller by means of a property, which it later uses to get the UserManager.
In conclusion, if you encounter static extension methods when you're unit testing, don't panic. Just whip out a wrapper class and interface to break that hard dependency. This is just one example of overcoming a dependency in existing code. However, when designing for new functionality, always try to think of how you're going to mock the classes you create.