Mocking static classes in .NET: Introducing Stathijack


Mocking static classes in .NET: Introducing Stathijack

Have you ever avoided using static classes, even though it made perfect sense, just because you knew it would be hell to create your unit tests? Well, good news then: there is now a tool that allows you to mock your static classes, just like you are used with other mocking frameworks. Or similarly, at least. With Stathijack, you can create a mock for a single static method, or even replace the entire class with a fake one. And the best part is that you don’t have to change your production code at all.

How does it work

Let’s suppose that we are developing a new software that specifically creates orange cats, because why not. We have created a static factory called OrangeCatFactory, which will provide all the orange cats we need. Also, we have a class called CatShop, which makes a new cat whenever a new customer wishes. Lastly, we have the ICat interface and the Cat class, which have the Meow method. Here’s what they look like:

Now we can move onwards with the test creation. In order to mock our static class, we first need to create a HijackRegister, which controls what we have mocked and allows us to remove those mocks later on. We then need to create an instance of the MockingHijacker, which will provide the mocking capabilities for us. With that in place, we can call the MockMethod, which takes the method name and a Func or Action with the desired new behavior. And that’s it!

Take notice that the number of parameters in the Action or Func must match exactly the number of parameters of the original methods. For example, in the current test code we don’t provide any parameters, so it works fine. However, if we were to define it as something like “(string parameter) => { return new NormalCat(); }”, it would not work. There are also some known issues that you can find in the GitHub repository. You can also find more examples in FactoryUserTests test class, under the Samples folder.

Considerations

The tool is at its infant stage, so there are plenty of features to be added and probably bugs to be fixed. Please submit your suggestions or report bugs under the Issues section, I would really appreciate that. Hope that you find Stathijack useful!


Leave a Reply

Your email address will not be published. Required fields are marked *