__init__ for unittest. TestCase

我想添加一些东西到什么 unittest.TestCase类被初始化后,但我不知道如何做到这一点。

现在我要做的是:

#filename test.py


class TestingClass(unittest.TestCase):


def __init__(self):
self.gen_stubs()


def gen_stubs(self):
# Create a couple of tempfiles/dirs etc etc.
self.tempdir = tempfile.mkdtemp()
# more stuff here

我希望对于整个测试集,所有存根只生成一次。我不能使用 setUpClass(),因为我正在处理 Python 2.4(我也没能在 Python 2.7上处理它)。

我做错了什么?

我得到了这个错误:

 `TypeError: __init__() takes 1 argument (2 given)`

... 和其他错误时,我移动所有的存根代码到 __init__当我运行它与命令 python -m unittest -v test

90904 次浏览

试试这个:

class TestingClass(unittest.TestCase):


def __init__(self, *args, **kwargs):
super(TestingClass, self).__init__(*args, **kwargs)
self.gen_stubs()

您正在重写 TestCase__init__,因此您可能希望让基类为您处理参数。

安装 unittest2并使用该包的 unittest。

import unittest2

然后使用 setupModule/tearDownModule 或 setupClass/tearDown 类 用于特殊的初始化逻辑

更多信息: http://www.voidspace.org.uk/python/articles/unittest2.shtml

您创建的集成测试也很可能比单元测试更多。 为测试选择一个好的名称来区分它们,或者放在不同的容器模块中。

只是想添加一些关于覆盖

unittest.TestCase

该函数将在测试类中的每个方法之前调用。请注意,如果您想添加一些代价高昂的计算,这些计算应该在运行所有测试方法之前执行 一次,请使用 SetUpClass类方法

@classmethod
def setUpClass(cls):
cls.attribute1 = some_expensive_computation()

该函数将在类的所有测试方法之前调用 一次。有关在每个测试方法之前调用的方法,请参见 setUp