Why is using static methods not suitable for unit testing?

I've heard that creating an object with static methods is not suitable for unit testing. For example, we have the following hierarchy:

public abstract class Base{

    public static Base createConcrete(){
        return new Concrete();
    }

    public static Base createSuperConcrete(){
        return new SuperConcrete();
    }
}

public class Concrete extends Base { }

public class SuperConcrete extends Base { }

      

It is better to use a FactoryMethod instance instead. Why is using methods static

causing too much pain in unit tests? Could anyone give an example?

+3


source to share


1 answer


The main flaw in your approach is that there is no way to make your class clients Base

work with anything other than Concrete

and SuperConcrete

.

Think of the following example: both Concrete

so SuperConcrete

do require initialization of some expensive resources (database connections or whatever).

Classes that use the class Base

will invoke all the heavy lifting when called Base.createConcrete()

, so for this reason you can only have integration tests.



On the other hand, if you create*Concrete

were instance methods, you could provide your clients with a mocked / dummy implementation Base

that creates lightweight "concrete" instances, enough to run your test cases. You can use frameworks like Mockito, or just create dummy implementations by hand.

Measuring static methods are only possible with truly intrusive tools like PowerMock

(if possible at all) and thus makes your test code unnecessarily complex.

+1


source







All Articles