If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?
I’d like to reduce test code duplication, but still ‘stay true’ to the principles of Unit testing.
What would you consider best practice? I’m using NUnit, but I suppose examples from any Unit testing framework would be valid
If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.
Lets go with a smarter route instead; if your goal is to avoid code and test code duplication you might want to create an abstract class instead that handles the recurring code.
E.g. you have the following interface:
You might want to create an abstract class:
Testing that is easy; implement the abstract class in the test class either as an inner class:
…or let the test class extend the abstract class itself if that fits your fancy.
Having an abstract class take care of common code that an interface implies gives a much cleaner code design.
I hope this makes sense to you.
As a side note, this is a common design pattern called the Template Method pattern. In the above example, the template method is the
CommonCodemethod andSpecificCodeis called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.A lot of frameworks rely on this behavioral pattern, e.g. ASP.NET where you have to implement the hooks in a page or a user controls such as the generated
Page_Loadmethod which is called by theLoadevent, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words ‘load’, ‘init’, or ‘render’ is called by a template method.