Base Class Logic – Implementing Common Logic in Object-Oriented Design

mockingobject-orientedobject-oriented-designunit testing

Background

In the documentation of a project I'm working on I came across the following sentence which immediately triggered an alarm for me:

when having several concrete classes that inherits from the same base class, logic which is common for all sub classes should NOT be implemented in the base class.

This is a pretty bold statement which kind of conflicts with everything I think of OOP.

The reason stated was testability. It said that when writing unit tests, if a common logic is implemented in the base class, it will be tested multiple times for each concrete sub class and cannot be mocked out.

Question

Where or how can one implement a common logic for multiple sub classes so it can be easily mocked when they are being tested?

Best Answer

You stumbled on one of the Bigger problems that tends to get swept under the rug in unit testing/TDD discussions. Well designed code from an object oriented perspective is generally hard to unit test, code that is easy to write unit tests for usually is compromising some paradigms of object oriented design.

Most approaches to unit testing tend to drive towards a design that makes unit testing easier, which isn't bad depending on what rules you bend/break. These designs tend to over expose methods so they can be more easily isolated, using interfaces or utility classes to handle common code.

Dependency injection is one of the more popular ways to handle these situations. Here is a pretty simple example in C#. Essentially rather than inheriting directly from a base class, each class will instead implement an interface that is dependent upon an object that handles the common operations. This way you can simply pass MyMockedCommonClass instead of MyCommonClass in your unit tests. This also allows your code to still be pretty Object Oriented friendly.

Related Topic