python中的unittest housekeeping

时间:2012-09-07 10:14:29

标签: python unit-testing fixtures

我有一个unittest测试文件,其中包含四个测试类,每个测试类负责在一个特定的类上运行测试。每个测试类都使我们使用完全相同的set-upteardown方法。 set-up方法相对较大,启动了大约20个不同的变量,而teardown方法只是将这20个变量重置为初始状态。

到目前为止,我已经将二十个变量放在四个setUp类中的每一个中。这有效,但不是很容易维护;如果我决定更改一个变量,我必须在所有四个setUp方法中更改它。然而,我寻找更优雅的解决方案却失败了。理想情况下,我只想输入我的二十个变量,在我的四个setup方法中调用它们,然后在我的每个测试方法之后将它们拆除。考虑到这一点,我尝试将变量放在一个单独的模块中并在每个setUp中导入它,但当然变量只能在setup方法中使用(另外,尽管我无法确切地说明原因,这感觉像是一种潜在的容易出错的方式

from unittest import TestCase

class Test_Books(TestCase):
    def setup():
        # a quick and easy way of making my variables available at the class level
        # without typing them all in

    def test_method_1(self):
        # setup variables available here in their original state
        # ... mess about with the variables ...
        # reset variables to original state

    def test_method_2(self):
        # setup variables available here in their original state
        # etc...

    def teardown(self):
        # reset variables to original state without having to type them all in



class Books():
    def method_1(self):
        pass

    def method_2(self):
        pass

2 个答案:

答案 0 :(得分:1)

我要做的是让4个测试类成为一个基础测试类的子类,它本身就是TestCase的子类。然后把setip和teardown放在基类中,其余的放在其他类中。

e.g。

class AbstractBookTest(TestCase):
   def setup():
      ...

class Test_Book1(AbstractBookTest):
   def test_method_1(self):
     ...

另一种选择就是让一个类不是你所拥有的四个,除非你给出分裂的理由,否则这里似乎更合乎逻辑。

答案 1 :(得分:1)

另一种方法是将二十个变量放入一个单独的类中,在类的__init__中设置值,然后以class.variable的形式访问数据,这是在{{中设置变量s的唯一地方。 1}}并且代码不重复。

__init__

如果二十个数据彼此相关,则该解决方案更有意义。此外,如果您有二十条数据,我希望它们是相关的,因此它们应该在实际代码中组合而不仅仅是在测试中。