Share via


Test Class Inheritance Revisited

Some years ago I used to use inheritance in my unit test class design, mainly to avoid code duplication.

When VS2005 introduced unit tests, this was one of the most requested features.. but with time, it has been forgotten.

Today, I was creating some integration tests that called a WCF service, so I was changing the configuration over and over to switch from my local instance of the service and the “remote” instance.

Because WCF requires that, the configuration was more complex than just change a URL. So I decided to have a couple a test classes to execute against different environments, so I will change the WCF configuration programatically.

wait… how can I have a two test classes with the same testmethods but avoid code duplication? So I remembered the test inheritance pattern. Here we go:

First, create an abstract class and decorate it with the TestClass Attribute. Then add a virtual method as factory to create your “target”. After that you can create your derived classes and override the virtual method:

image

With this approach, you have a single class where you can implement your test methods, and in the other hand you will have two different versions of each test:

image