Polymorphic test setup with template method

C#, .Net, Refactoring, Design Patterns, Testing


We had a kind of duplication in our tests that we didn’t know how to deal with. The refactoring Introduce Polymorphic Creation with Factory Method explained by Joshua Kerievsky in his brilliant book “Refactoring to Patterns” gave us the solution to avoid duplicated tests.

These tests are very similar, the differences are in lines 8 and 25, and also in lines 13 and 30. The first test tries to change the color of a configuration, whereas the second one tries to change the interior. Part of the handling business logic is the same. This is just one scenario but we had many others with the same expected behavior for color, interior, equipment, and more. Eventually there would be a lot of duplication.

After refactoring, we have a base abstract class with the tests, exposing template methods that derived classes have to implement in order to populate the catalog and also to execute the corresponding action:

The base class ConfigurationTests contains just helper methods such as ExecuteChangeColor, or ExecuteChangeInterior, but no tests at all. Otherwise tests would run twice.

Originally published in Carlos Blé's blog.