Is static method evil?
static method in unit test
This is an old discussion. It comes to my mind frequently while I’m writing unit test these days. Do I need to convert all static methods into instance methods to simplify mocking and stubbing?
What makes static evil when it comes to unit test. Imagine one method invoking another static method, how could it be test effectively? The static method is now a collaborator of the method under test. But since it’s called directly within the function body, there’s no straightforward way to stub it for testing. In another saying, it cannot be injected.
It’s not the static method evil but a question whether the method should be static or not. If a function is pure without side effects, it can be a static method which can be used in test directly. If the function has side effects like disk IO, network IO, etc, then it must not be a static method. It should lie in a class and we must refactor the code to turn the collaborator into a dependence which can be injected. This approach ensures the code is testable.
By the way, mockito5 has made inline-mockmaker the default MockMaker which supports mockitStatic
, a feature known to few people. It can be quite powerful when coming to test static method but it’s not applicable in a multi-threaded context.