1

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?

Pål Brattberg
  • 4,568
  • 29
  • 40
S. Valmont
  • 13
  • 3

2 Answers2

2

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).

Pål Brattberg
  • 4,568
  • 29
  • 40
0

It depends on the language. For instance, in a language like Java calling an instance method on a concrete class is not bad for testing at all, because a proxy instance for that concrete class can be generated, allowing the calls to be intercepted (and typically, mocked out) effectively. In fact, many frameworks use this proxy facility to inject their own code before/after user code in order to provide features like dependency injection and AOP support.

aroth
  • 54,026
  • 20
  • 135
  • 176