Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test subclasses

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.

like image 918
DRock Avatar asked Sep 17 '11 16:09

DRock


2 Answers

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.

like image 172
philant Avatar answered Sep 18 '22 14:09

philant


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.

like image 43
Peter vd Merwe Avatar answered Sep 20 '22 14:09

Peter vd Merwe