How to mock a static member for test-driven development – level 400

If you are interested in mocking a static member or class in order to facilitate testing a component in isolation, you are traveling down the wrong path.  First, to be blunt, you cannot mock a static.  Static members belong to the AppDomain, and are not replaceable instances.  For instance, if I have a class with static methods called SqlHelper (like version 2 of the DAAB), and I want to unit test a class that calls methods on SqlHelper, I’m stuck.  I can’t do it.  SqlHelper’s static methods call directly into data access code, so now anything that calls SqlHelper has a transitive dependency on the data access code (and most likely the database behind it). 


So you have code that can’t be tested in isolation.  What do you do? 



  • Don’t waste you time trying to find a solution to mocking the static members of SqlHelper.  You can’t do it.  Just like you can’t run Java Swing code inside a WinForms .Net project – there’s no point in searching for a solution because one doesn’t exist). 
  • Refactor your code because your component is highly coupled.  You desire loosely coupled code.  Change your SqlHelper class’s static members into instance members, or if you can’t, wrap it in another class – let’s call this SqlRunner.
  • Accept an instance of SqlRunner in the constructor of the component you are testing; save it in a class-level variable.
  • Unit test to your heart’s content.

It’s really that simple.  In your test, you can create a dynamic mock of the SqlRunner class and pass that into the constructor of your tested component.  Your component will now call out to your mock, and you have succeeded in testing your component in isolation. 


You may be wondering what to do if you need to call some static members in the .Net framework.  For instance, what about HttpContext.Current in a web control?  Current is a static property that returns the current instance of the HttpContext class.  You do not want to call that property directly in your code if you ever hope to test it.  In that case, use the same technique as above with a thin wrapper class that knows how to get HttpContext.Current.


If you still aren’t convinced about the rigidity of statics in code, feel free to keep searching, but when you come back around and follow the above steps, come back and leave a comment.