unit testing class hierarchies

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Tue Oct 2 08:27:11 EDT 2012


Greetings!

I'm trying to unittest a class hierachy using Python 2.7. I have a 
common baseclass Base and derived classes D1 and D2 that I want to test. 
The baseclass in not instantiatable on its own. Now, the first approach 
is to have test cases TestD1 and TestD2, both derived from class TestCase:

class TestD1(unittest.TestCase):
     def test_base(self):
         ...
     def test_r(self):
         ...
     def test_s(self):
         ...

class TestD2(unittest.TestCase):
     def test_base(self):
         # same as above
         ...
     def test_x(self):
         ...
     def test_y(self):
         ...

As you see, the code for test_base() is redundant, so the idea is to 
move it to a baseclass:

class TestBase(unittest.TestCase):
     def test_base(self):
         ...

class TestD1(TestBase):
     def test_r(self):
         ...
     def test_s(self):
         ...

class TestD2(TestBase):
     def test_x(self):
         ...
     def test_y(self):
         ...

The problem here is that TestBase is not a complete test case (just as 
class Base is not complete), but the unittest framework will still try 
to run it on its own. One way around this is to not derive class 
TestBase from unittest.TestCase but instead use multiple inheritance in 
the derived classes [1]. Maybe it's just my personal gut feeling, but I 
don't like that solution, because it is not obvious that this class 
actually needs to be combined with a TestCase class in order to 
function. I would rather tell the unittest framework directly that it's 
not supposed to consider this intermediate class as a test case, but 
couldn't find a way to express that clearly.

How would you do this?

Uli


[1] in C++ I would call that a "mixin"




More information about the Python-list mailing list