gpt4 book ai didi

Python unittest - setUpClass() 给我带来了麻烦 - 为什么我不能这样继承?

转载 作者:IT老高 更新时间:2023-10-28 21:31:34 29 4
gpt4 key购买 nike

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

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 :

A class method called before tests in an individual class run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():

@classmethod
def setUpClass(cls):
...

See Class and Module Fixtures for more details.

您的版本缺少 @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 unittest - setUpClass() 给我带来了麻烦 - 为什么我不能这样继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14044474/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com