Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit-test inheriting objects?

When you use composition, then you can mock the other objects from which your class-under-test depends, but when you use inheritance, you can't mock the base class. (Or can you?)

I generally try to prefer composition over inheritance, but sometimes inheritance really seems like the best tool for the job - well, at least until it comes to unit-testing.

So, how do you test inheritance? Or do you just trash it as untestable and use composition instead?

Note: I mostly use PHP and PHPUnit, so help on that side is most appreciated. But it would also be interesting to know if there are solutions to this problem in other languages.

like image 206
Rene Saarsoo Avatar asked Sep 19 '08 09:09

Rene Saarsoo


2 Answers

Use a suite of unit tests that mirrors the class hierarchy. If you have a base class Base and a derived class Derived, then have test classes BaseTests and derived from that DerivedTests. BaseTests is responsible for testing everything defined in Base. DerivedTests inherits those tests and is also responsible for testing everything in Derived.

If you want to test the protected virtual methods in Base (i.e. the interface between Base and its descendent classes) it may also make sense to make a test-only derived class that tests that interface.

like image 193
munificent Avatar answered Oct 26 '22 08:10

munificent


As long as you don't override public methods of the parent class, I don't see why you need to test them on all the subclasses of it. Unit test the methods on the parent class, and test only the new methods or the overriden ones on the subclasses.

like image 38
gizmo Avatar answered Oct 26 '22 09:10

gizmo