我有如下的单元测试代码:

import unittest

class MyUnitTest(unittest.TestCase):
    def setUpClass(self):
        do_something_expensive_for_all_sets_of_tests()

class MyFirstSetOfTests(MyUnitTest):
    def setUpClass(self):
        super(MyFirstSetOfTests, self).setUpClass()
        do_something_expensive_for_just_these_first_tests()

    def test_one(self):
        ...

    def test_two(self):
        ...

class MySecondSetOfTests(MyUnitTest):
    def setUpClass(self):
        super(MySecondSetOfTests, self).setUpClass()
        do_something_expensive_for_just_these_second_tests()

    def test_one(self):
        ...

    def test_two(self):
        ...

if __name__ == '__main__':
    unittest.main()

当我尝试运行此代码时,出现如下错误:
======================================================================
ERROR: setUpClass (__main__.MyFirstSetOfTests)
----------------------------------------------------------------------
TypeError: unbound method setUpClass() must be called with MyFirstSetOfTests instance as first argument (got nothing instead)

----------------------------------------------------------------------

最佳答案

setUpClass必须是一个类方法。从documentation:



您的版本缺少 @classmethod decorator:

class MyUnitTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        do_something_expensive_for_all_sets_of_tests()

class MyFirstSetOfTests(MyUnitTest):
    @classmethod
    def setUpClass(cls):
        super(MyFirstSetOfTests, cls).setUpClass()
        do_something_expensive_for_just_these_first_tests()

引发该错误是因为在类而非实例上调用了MyFirstSetOfTests.setUpClass(),但是您没有将方法标记为classmethod,因此未在自动self参数中传递该方法。在上面的更新代码中,我改用了cls,以反射(reflect)该名称引用了类对象。

关于python - Python unittest-setUpClass()给我带来麻烦-为什么我不能这样继承?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14044474/

10-10 14:39