6

I heard that creating object with static methods is not good for unit-testing. For instance, 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's better use instance FactoryMethod instead. Why does using static methods cause too much pain in unit tests? Couldn't someone give an example?

4
  • In your example, it doesn't matter so much that the methods are static, because your clients will already be tied to the method names which name the actual class being instantiated. Commented May 30, 2015 at 9:19
  • 1
    @quamrana So in what example it does matter? Commented May 30, 2015 at 9:19
  • 2
    Have you googled first? Wasn't this or this helpful? Commented May 30, 2015 at 9:21
  • 7
    static methods cannot be overridden, so a unit test cannot supply different mock objects for different tests. Commented May 30, 2015 at 9:21

1 Answer 1

1

The main drawback of your approach is that there's no way to make the clients of your Base class work with anything other than Concrete and SuperConcrete.

Think of the following example: both Concrete and SuperConcrete require some expensive resources to initialize (database connections or whatever).

The classes that use the Base class will trigger all that heavy-lifting on calling Base.createConcrete() -- so you can only have integration tests for that reason.

On the other hand, if create*Concrete were instance methods, you could provide your clients with a mocked/dummy implementation of Base that creates lightweight "concrete" instances, just enough for running your test cases. You'll be able to use frameworks like Mockito or just create dummy implementations by hand.

Mocking static methods is only possible with really intrusive tools like PowerMock (if possible at all) and thus makes your test code unnecessarily complex.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.