In his book Java Design, Peter Coad says that one of the five criteria a subclass should meet is that the subclass “does not subclass what is merely a utility class (useful functionality you’d like to reuse).” For an example in Java, he says that making one of your domain classes a subclass of the Observable class is a violation of his rule: “Observable is a utility class, a collection of useful methods–nothing more.”
In that context, here are some example test classes patterned after actual tests I’ve written:
class BaseDataGeneratorTestCase (unittest.TestCase):
def _test_generate_data(self, generator, expected_value):
# Imagine there's a lot more code here, making it
# worthwhile to factor this method out.
assert generator.generate_data() == expected_value
class DataGeneratorTests (BaseDataGeneratorTestCase):
def test_generate_data(self):
self._test_generate_data(DataGenerator(), "data")
class VariantDataGeneratorTests (BaseDataGeneratorTestCase):
def test_generator_data(self):
self._test_generate_data(VariantDataGenerator(),
"different data")
Though this example is trivial, consider that the real tests and their surrounding system are, of course, much more complex. I think this example is usable as a vehicle to try and clear up some of my confusion about the proper use of inheritance.
Is subclassing BaseDataGeneratorTestCase a bad idea? Does it qualify as just “useful functionality [I’d] like to reuse”? Should _test_generate_data just be a function, not in any class?
Basically you can solve the problem any way you like. OOP is just a paradigm that’s supposed to help you design things in a clearer and maintainable way.
So, the question you should ask yourself any time you want to use inheritance they are have they same role, and you just want to add functionality ? or do you want to just use the nice methods in the “base” class ?
It’s just a matter of concept, and in your little example it could go either way because they have the same concept, but basically, you’re just using the base class as a utility.
If you want the base class to actually be a base class you should design it so every inherited class will behave the similarly.
I do agree that conceptually it would make sense to have a unit test baseclass for all the tests that work similarly.