Python单元测试继承 - 抽象测试类

4
我需要在Python中使用unittest编写一些测试。我正在测试2个类AB的行为,它们的行为有很多重叠,因为它们都是C的子类,而C是抽象的。我真的想能够编写3个测试类:ATestCaseBTestCaseAbstractTestCase,其中AbstractTestCase定义了ATestCaseBTestCase的公共设置逻辑,但本身不运行任何测试。ATestCaseBTestCase将是AbstractTestCase的子类,并定义特定于AB的行为/输入数据。

是否有一种方法可以通过Python unittest创建一个抽象类,该类可以通过继承TestCase来处理设置功能,但实际上不运行任何测试?


为什么不测试C,而不是在AB中测试相同的功能?或者,TestCase可以成为AB测试用例的混合体,以便unittest实际上无法发现AbstractTestCase - jonrsharpe
2个回答

3
当然,这样构建肯定会起作用:
class BaseTestCase(unittest.TestCase):
    def setUp(self):
        pass  # common teardown

    def tearDown(self):
        pass  # common teardown


class ATestCase(BaseTestCase):
    def test1(self):
        pass


class BTestCase(BaseTestCase):
    def test1(self):
        pass

如果在BaseTestCase中需要ATestCaseBTestCase的知识,只需在子类中覆盖某些方法并在超类中使用即可。

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        self.instance = self._create_instance()

    def _create_instance(self):
        raise NotImplementedError()


class ATestCase(BaseTestCase):
    def _create_instance(self):
        return A()


class BestCase(BaseTestCase):
    def _create_instance(self):
        return B()

请注意,如果在BaseTestCase中实现了任何test_(self)方法,当被自动化运行程序发现时,这些方法将会运行(并由于setUp失败而失败)。
作为一种解决方法,您可以在抽象测试的setUp子句中使用skipTest,并在子类中覆盖它。
class BaseTestCase(unittest.TestCase):
    def setUp(self):
        self.instance = self._create_instance()

    def _create_instance(self):
        self.skipTest("Abstract")

    def test_fromBase(self):
        self.assertTrue(True)

请注意,跳过test_fromBase(例如通过装饰器)并不好,因为“应该跳过测试”的逻辑将被所有子类继承。

我通过检查类来在 setUp 中跳过测试:if self.__class__ == BaseTestCase: self.skipTest("Skip base class") - dfrankow

2
我尝试了Łukasz的答案,它可以工作,但我不喜欢“OK(SKIP =<number>)”消息。对于我自己对测试套件的渴望和目标,我不想让自己或别人开始信任任何特定数量的跳过测试,也不信任并深入测试套件并询问为什么某些东西被跳过,并且总是?有意为之吗?对我来说,这是一个非起点。
我碰巧只使用nosetests,并且按照惯例,以_开头的测试类不会运行,因此命名我的基类为_TestBaseClass就足够了。
我在Pycharm中使用Unittests和py.test尝试了这个方法,但两者都尝试运行我的基类及其测试,导致错误,因为抽象基类中没有实例数据。也许具有这些运行程序特定知识的人可以创建一个套件或其他东西,绕过基类。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接