DRock
DRock

Reputation: 285

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.

Upvotes: 16

Views: 8617

Answers (2)

philant
philant

Reputation: 35816

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.

Upvotes: 12

Peter vd Merwe
Peter vd Merwe

Reputation: 300

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.

Upvotes: 6

Related Questions