The whole idea behind unit testing is to isolate the system under test (SUT) so you can control all the variables and be able to simulate different scenarios to see how your system behaves. The isolation process usually involves initializing a fake/stub instance and injecting it into the SUT. However with statics, there is no instance to initialize so there is nothing to mock. Your class is tightly bound to that static method and there is no way to free it and isolate the system without doing extra work or using specialized mocking frameworks. (On a side note, I don’t think using these specialized mocking framework is a good idea either, because they promote bad software design. If you follow SOLID design principles then unit testable architecture comes naturally).
Lets look at an example where the method I want to test calls out to some static method and see what problems it creates.

Lets assume that we want to verify that the 15% discount is being applied correctly. We need a way for the static Validate() method to return true in order to get to the discount calculation logic. You could extract the call to the static method into a protected virtual method in order to introduce seam, which we can use during testing, but that’s writing more code which we are trying to avoid because chances are most developers wont even bother. You could go into the static Validate() method and try to figure out what constitutes a valid accountId.

In this case it’s not that complicated either – I’ll just pass in 5004 as the accountId in my test, so what’s wrong. Well, what you have done is made your test very brittle, because the ApplyDiscount() test could fail if anything changes in the static Validate() method. Imagine the static Validate() method internally called some other static method, now you are just going deeper and deeper into the rabbit hole and you might never get out. Also there is no way to write unit test for static methods. So please stop writing functional utility methods and embrace object oriented programming, it’s about time don’t you think!

Leave a comment