NYCPHP Meetup

NYPHP.org

[nycphp-talk] Why do unit tests not inherit?

Michael Hernandez sequethin at gmail.com
Fri Nov 15 10:43:26 EST 2013


On Nov 15, 2013, at 10:26 AM, "Gary A. Mort" <garyamort at gmail.com> wrote:
> 
> Is there a reason that most unit tests published for PHP Open Source projects do not use OOP programming?
> 
> --
> Class Pets
> Class Dogs extends Pets
> Class Cats extends Pets
> 
> 
> Unit tests written for those classes generally are defined like
> Class TestPets extends TestCase
> Class TestDogs extends TestCase
> Class TestCats extends TestCase
> 
> 
> It seems to me that it should be
> Class TestPets extends TestCase
> Class TestDogs extends TestPets
> Class TestCats extends TestPets
> 
> That way if the Pets base class is given a new method based on a method in Dogs but with subtle differences, by inheriting the TestPets unit tests you will immediately find out that the Dogs class is failing the Pets unit tests and either needs to be changed to match or if it is supposed to be different, the test from TestPets has to be disabled in TestDogs.
> 
> I'm trying to wrap my brain around this and wondered if there is some valid reason for not using inheritance for tests in this way - or if it is just that for whatever reason when programmers first started writing unit tests they got stuck in a functional rather than object oriented mindset?
> 
> -Gary
> ________________________________

You could have a hierarchy like the one you describe but I wouldn't work too hard to make that fit. Tests should be as simple as possible and thus shouldn't require anything special to get their work done (yes, inheritance is pretty special). Essentially you want to avoid complex inheritance, logic, looping, etc., in order to avoid your tests needing tests or documentation of their own.

That being said, if you find that all "pet tests" require some common set up, you might refactor in the way you mentioned above. Personally, I would avoid that until absolutely necessary. I would even go so far as to say that sticking to DRY isn't as important as having clear tests that not only give you confidence that your code works but also serve as living documentation. Having important bits squirreled away into base classes can make things harder to read sometimes. Whether or not having code in another class separate from your test increases the clarity of your code is entirely up to the reader, of course ;)

--Mike H


More information about the talk mailing list