Search code examples
.netvisual-studio-2010unit-testingliskov-substitution-principle

Can I implement a series of reusable tests to test an interface's implementation?


I am writing a series of collection classes in C#, each of which implement similar custom interfaces. Is it possible to write a single collection of unit tests for an interface, and automatically run them all on several different implementations? I would like to avoid any duplicated testing code for each implementation.

I'm willing to look into any framework (NUnit, etc.) or Visual Studio extension to accomplish this.


For those looking to do the same, I posted my concrete solution, based off of avandeursen's accepted solution, as an answer.


Solution

  • Yes, that is possible. The trick is to let your unit class test hierarchy follow the class hierarchy of your code.

    Let's assume you have an interface Itf with implementing classes C1 and C2.

    You first create a test class for Itf (ItfTest). To actually exercise the test, you need to create a mock implementation of your Itf interface.

    All tests in this ItfTest should pass on any implementation of Itf (!). If not, your implementation does not conform to the Liskov Substitution Principle (the "L" in Martin's SOLID principles of OO design)

    Thus, to create a test case for C1, your C1Test class can extend ItfTest. Your extension should replace the mock object creation with the creation of a C1 object (injecting it in, or using a GoF factory method). In this way, all ItfTest cases are applied to instances of type C1. Furthermore, your C1Test class can contain additional test cases specific to C1.

    Likewise for C2. And you can repeat the trick for deeper nested classes and interfaces.

    References: Binder's Polymorphic Server Test pattern, and McGregor's PACT -- Parallel Architecture for Component Testing.