如何为不同的类运行相同的测试用例? [英] How to run the same test-case for different classes?

查看:32
本文介绍了如何为不同的类运行相同的测试用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类共享一些不变量并有一个通用接口,我想为每个类自动运行相同的测试.

I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.

举个例子,假设我有几个类实现了不同的数据集分区方法.这里的共同不变式是,对于所有这些类,所有分区的并集应该等于原始数据集.

As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these classes the union over all partitions should equal the original data-set.

我目前拥有的看起来像这样:

What I currently have looks something like this:

class PartitionerInvariantsTests(unittest.TestCase):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set

    def impl(self, partitioner):
        self.assertEqual(self.testDataSet, 
                         chain.from_iterable(partitioner(self.testDataSet))

然后,我添加了一个不同的函数,该函数为我想使用该类的实例测试的每个类调用 impl.当为多个测试功能执行此操作时,此问题变得明显.假设我有 5 个测试函数和 5 个要测试的类.这将使 25 个函数在调用所有测试时看起来几乎相同.

Then I add a different function that calls impl for each of the classes I want to test with an instance of that class. The problem with this becomes apparent when doing this for more than one test-function. Suppose I have 5 test-functions and 5 classes I want to test. This would make 25 functions that look almost identical for invoking all the tests.

我想到的另一种方法是将模板实现为超类,然后为我要测试的每个类创建一个子类.子类可以提供用于实例化类的函数.这样做的问题是默认的测试加载器会将(不可用的)基类视为有效的测试用例并尝试运行它,但会失败.

Another approach I was thinking about was to implement the template as a super-class, and then create a sub-class for each of the classes I want to test. The sub-classes could provide a function for instantiating the class. The problem with that is that the default test-loader would consider the (unusable) base-class a valid test-case and try to run it, which would fail.

那么,您有什么建议?

P.S.:我使用的是 Python 2.6

P.S.: I am using Python 2.6

推荐答案

您可以使用多重继承.

class PartitionerInvariantsFixture(object):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set
        super(PartitionInvariantsFixture, self).setUp()

    def test_partitioner(self):
        TestCase.assertEqual(self.testDataSet, 
                     chain.from_iterable(self.partitioner(self.testDataSet))

class MyClassTests(TestCase, PartitionerInvariantsFixture):
    partitioner = Partitioner

这篇关于如何为不同的类运行相同的测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆