Search code examples
testingmethodsstaticinstanceconcrete

Concrete Instance Methods Are Just as Bad as Static Methods for Testing, Right?


If method A() calls static method B(), this is bad because the two are tightly coupled, correct?

But if, instead of calling B(), A() called a non-static method C() of some concrete class, this would be equally bad for testing, correct? Because now A() is coupled to the concrete class that owns C().

The only good scenario happens when interfaces (i.e., dependency injection) are used, and A() calls the interface's method.

Do I have it right? Are there any other reasons static methods are bad for testing?


Solution

  • The first scenario is "bad" because it makes is hard to exchange what B()is being called.

    The second scenario is possibly not quite as "bad" because, depending on how you get your instance of the class that owns C(), you might be able to exchange that object for another (say a subclass).

    The third scenario is typically "best" since it allows you to easier change the implementation of A(), but this is only true if there is no hard-coded construction of a concrete class providing A() (i.e. only tru if dependency injection is actually used).