Should I test inherited methods

inheritancetesting

Suppose I have a class Manager derived from a base class Employee, and that Employee has a method getEmail() that is inherited by Manager. Should I test that the behaviour of a manager's getEmail() method is in fact the same as an employee's?

At the time these tests are written the behaviour will be the same, but of
course at some point in the future someone might override this method, change its behaviour, and therefore break my application. However it seems a bit strange to essentially test for the absence of meddling code.

(Note that testing Manager::getEmail() method does not improve code coverage (or indeed any other code quality metrics (?)) until Manager::getEmail() is created/overridden.)

(If the answer is "Yes", some information about how to go about managing tests that are shared between base and derived classes would be useful.)

An equivalent formulation of the question:

If a derived class inherits a method from a base class, how do you express (test) whether you're expecting the inherited method to:

  1. Behave in exactly the same way as the base does right now (if the behaviour of the base changes, the behaviour of the derived method doesn't);
  2. Behave exactly the same way as the base for all time (if the behaviour of the base class changes, the behaviour of the derived class changes as well); or
  3. Behave however it wants to (you don't care about the behaviour of this method because you never call it).

Best Answer

I'd take the pragmatic approach here: If someone, in the future, overrides Manager::getMail, then it is that developer's responsibility to provide test code for the new method.

Of course that's only valid if Manager::getEmail really has the same code path as Employee::getEmail! Even if the method is not overridden, it might behave differently:

  • Employee::getEmail could call some protected virtual getInternalEmail which is overridden in Manager.
  • Employee::getEmail could access some internal state (e.g. some field _email), which can differ in the two implementations: For example, the default implementation of Employee could ensure that _email is always firstname.lastname@example.com, but Manager is more flexible in assigning mail addresses.

In such cases, it is possible that a bug manifests itself only in Manager::getEmail, even though the implementaion of the method itself is the same. In that case testing Manager::getEmail separately could make sense.