Friday, February 10, 2006

Creating an interface for testing

When following some common unit testing guidelines you will often need to create interfaces for the purpose of testing.

A common example of this occurs when you use constructor dependency injection. For example, if you have a Foo class that takes a Bar as a constructor argument.
class Foo...
public Foo(Bar bar)
{
this.bar = bar;
}
..
}
In the above example Foo cannot be tested without creating an instance of the Bar class. However, the dependency could be mocked or stubbed (depending upon intent) if Foo instead depended upon an interface.
class Foo...
public Foo(IBar bar)
{
this.bar = bar;
}
..
}
Unfortunately, this approach is often met with criticism.

The common complaints include.
Using an interface has additional positives.
This is a simple concept, but it's often a tripping point. Don't be afraid of the overhead required to use an interface when it will improve your ability to write quality software.


Comments:
Actually using an interface in the first place is considered good design by many developers (myself included) and testing be damned for adding it to the design. Honestly the high decoupling that the interface gives you in static languages is generally considered desired
 
I agree that using an interface in the first place is good design. GOF seemed to popularize the idea "to program to an interface, not an implementation." Unfortunately, I don't see this guideline followed as often as I'd prefer.

Perhaps my entry is better stated as "testing purposes" is another reason in favor of programming to an interface, not the main reason to program to an interface.
 
I can see why people complain if you give your interfaces such bad names.

A common code smell is classes and interfaces with the same name, but with some naming wart to avoid name clash. E.g. Foo and IFoo, or FooImpl and Foo. An interface is not a "header file" for a class; it represents a relationship between objects. What is that relationship? That's what the interface should be named after. What does an object do, and how? That's what a class should be named after.
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?