3

given a Python class hierarchy, say

class Base:
    def method1
    def method2
    def method3
    ...
class Derived1(Base)
class Derived2(Base)

etc.

and given that Base defines some common interface which is re-implemented differently in each Derived class. What would be the most straightforward way to unit test all member functions of all classes. Since i'm having a class hierarchy, i thought of doing something like...

class MyTestCase(unittest.TestCase):
    def testMethod1:
        ## Just as an example. Can be similar
        self.failUnless(self.instance.method1())
    def testMethod2
    ...

And then setting up the test suite with test cases for different instantiations of the class hierarchy But how do i get the "instance" parameter into the MyTestCase class?

4

2 回答 2

1

The skip decorator applies to all of the subclasses as well as the base class so you cannot simply tell unittest to skip the base. The simplest thing is probably to not have the base test class derive from TestCase at all:

import unittest

class Base: pass
class Derived1(Base): pass

class BaseTest(object):
    cls = None

    def setUp(self):
        self.instance = self.cls()

    def test_Method1(self):
        print("run test_Method1, cls={}".format(self.cls))

class TestParent(BaseTest, unittest.TestCase):
    cls = Base

class TestDerived1(BaseTest, unittest.TestCase):
    cls = Derived1

unittest.main()
于 2012-07-03T09:48:05.567 回答
0

You can build the same tests hierarchy

class BaseTest()
    cls = None

    def setUp(self):
        self.instance = self.cls()

    def test_Method1(self) 
        ...

class TestParent(unittest.TestCase, BaseTest):
    cls = Base


class TestDerived1(unittest.TestCase, BaseTest):
    cls = Derived1

...
于 2012-07-03T09:02:14.617 回答