我的代码:
class TestSystemPromotion(unittest2.TestCase):
@classmethod
def setUpClass(self):
...
self.setup_test_data()
..
def test_something(self):
...
def setup_test_data(self):
...
if __name__ == '__main__':
unittest2.main()
我得到的错误是:
TypeError: unbound method setup_test_data() must be called with TestSystemPromotion
instance as first argument (got nothing instead)
最佳答案
您不能从类方法中调用实例方法。要么考虑改用 setUp
,要么也使 setup_test_data
成为类方法。此外,最好调用参数 cls
而不是 self
以避免混淆 - 类方法的第一个参数是类,而不是实例。当调用 setUpClass
时,实例 (self
) 根本不存在。
class TestSystemPromotion(unittest2.TestCase):
@classmethod
def setUpClass(cls):
cls.setup_test_data()
@classmethod
def setup_test_data(cls):
...
def test_something(self):
...
或者:
class TestSystemPromotion(unittest2.TestCase):
def setUp(self):
self.setup_test_data()
def setup_test_data(self):
...
def test_something(self):
...
为了更好的理解,你可以这样想:cls == type(self)
关于python - 无法从 setUpClass 调用本地方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5938517/