16

What is the best way to unit test subclasses? Let's assume there's a base class for which I've already written tests and there are some number of subclasses that override some of the parent's behavior in public and/or protected methods.

Should the test class for my subclasses extend (and override test methods where appropriate) the test class for my base class so that all of the base class tests are applied? Otherwise, I would expect to have repeated test code.

DRock
  • 285
  • 2
  • 7

2 Answers2

12

According to the Liskov substitution principle, instances of the subclasses, should exhibit the same properties as the base class, and, thus, pass (all ?) the same unit tests.

I would run [perhaps not all, all that are relevant] the base class tests for each subclass. This can be achieved with a test helper.

Yes, subclassing the test class could be a good way to avoid duplication in the unit tests. Have a look at the Testcase superclass pattern.

Community
  • 1
  • 1
philant
  • 34,748
  • 11
  • 69
  • 112
  • 1
    Your assertion about how Liskov substition principle applies is incorrect. A subclass's method doesn't have to pass all of the base's unit tests, otherwise they'd be behaviourally identical. In which case what's the point of overriding base methods? – mo. Aug 12 '13 at 20:12
  • 7
    The original posting re the Liskov principle is correct. The subclass should pass all the unit tests for the superclass, *and more*. The additional tests reflect the added functionality of the subclass. Of course you can override a method in such a way as to violate Liskov, and in this case the relevant unit tests will fail. – ComDubh Oct 12 '13 at 20:36
6

It is difficult to see without an example, but I would test the base class in one set of tests, and then create new tests for the subclasses and just test the behaviour that differs.