Skip to main content
 首页 » 编程设计

Python 单元测试 : Nose @with_setup failing

2025年05月04日12xing901022

我正在做一些测试。我的一些测试函数有共同的设置,所以我决定我应该使用 nose.tools 中的 @with_setup 装饰器。我已将我的问题简化为:

from nose.tools import with_setup 
 
class TestFooClass(unittest.TestCase): 
   def setup_foo_value(self): 
      self.foo = 'foobar' 
 
   @with_setup(setup_foo_value) 
   def test_something(self): 
      print self.foo 

我收到以下错误:

$ python manage.py test tests/test_baz.py 
 
E 
====================================================================== 
ERROR: test_something (project.tests.test_baz.TestFooClass) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
  File "/Users/user/Coding/project-backend/project/../project/tests/test_baz.py", line 17, in test_something 
    print self.foo 
AttributeError: 'TestFooClass' object has no attribute 'foo' 
 
---------------------------------------------------------------------- 

这就像 setup_foo_value 根本没有运行。非常感谢任何帮助!

请您参考如下方法:

根据文档:

  • writing tests :“请注意,unittest.TestCase 子类不支持方法生成器”
  • testing tools : "with_setup 仅对测试函数有用,对测试方法或 TestCase 子类内部没有用"

所以你可以将你的测试方法移动到一个函数中,或者添加一个 setUp方法到你的类(class)。