Python单元测试:Nose @with_setup失败

Ale*_*dre 1 python unit-testing decorator nose

我正在做一些测试.一堆我的测试函数有共同的设置,所以我决定我应该使用@with_setupdecorator nose.tools.我把问题简化为:

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
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

$ 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'

----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

这就像setup_foo_value没有被运行一样.任何帮助将非常感激!

Sch*_*uki 13

根据文件:

  • 编写测试:"请注意子类中不支持方法生成器unittest.TestCase"
  • 测试工具:" 仅对测试函数with_setup有用,不适用于测试方法或TestCase子类内部"

因此,您可以将测试方法移动到函数中,也可以setUp向类中添加方法.