python - 无法从 setUpClass 调用本地方法

标签 python unit-testing

我的代码:

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/

相关文章:

python - 在 Windows 中的 Python 文件上混合 read() 和 write()

python - 从字典创建 Python DataFrame,其中键是列名,值构成行

python - 我应该如何在 zsh 中使用 argcomplete?

函数调用时Javascript模拟第三方 Node 库

javascript - 如何进行单元测试来查看 Angular 是否未定义?

C#创建字符串(指定长度)

java - 使用 GUICE 注入(inject) HttpClient 以在 Java 中获取模拟响应

python - 最长子串(用于三元组序列)

python - 保存为 pdf 时保留原始图像数据

c# - 当另一端关闭时套接字未注册