__init__为unittest.TestCase

ffl*_*ing 99 python unit-testing

我想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
Run Code Online (Sandbox Code Playgroud)

我希望在整个测试集中只生成一次所有存根.我无法使用,setUpClass()因为我正在使用Python 2.4(我无法在python 2.7上工作).

我在这做错了什么?

我收到此错误:

 `TypeError: __init__() takes 1 argument (2 given)` 
Run Code Online (Sandbox Code Playgroud)

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

kar*_*ikr 136

试试这个:

class TestingClass(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestingClass, self).__init__(*args, **kwargs)
        self.gen_stubs()
Run Code Online (Sandbox Code Playgroud)

您正在覆盖TestCase__init__,所以你可能想要让基类处理这些参数为您服务.

  • 你不应该在`setUp`中调用它而不是覆盖`__init__`吗? (21认同)
  • @karthikr我想为所有测试生成一次存根,而不是每次都为每次测试重新创建它们.某些测试甚至不会使用某些存根.我会使用setUpClass,但我不认为python 2.4支持它. (2认同)
  • 在这种情况下你也可以更明确一些(在我看来这有助于提高可读性)并使用:`unittest.TestCase .__ init __(self,*args,**kwargs)`而不是`super(TestingClass,self). __init __(*args,**kwargs)` (2认同)

小智 10

Just wanted to add some clarifications about overriding the init function of

unittest.TestCase
Run Code Online (Sandbox Code Playgroud)

The function will be called before each method in your test class. Please note that if you want to add some expensive computations that should be performed once before running all test methods please use the SetUpClass classmethod

@classmethod
def setUpClass(cls):
    cls.attribute1 = some_expensive_computation()
Run Code Online (Sandbox Code Playgroud)

This function will be called once before all test methods of the class. See setUp for a method that is called before each test method.