Pytest在夹具前调用setup()
问题描述:
我在用pytest单元测试时遇到困难。Pytest在夹具前调用setup()
我使用的是测试类是这样的:
class TestMyApp(object):
def setup(self):
self.client = mock_client()
@pytest.fixture
def client_item(self):
return self.client.create_item('test_item')
def test_something1(self, client_item):
# Test here.
pass
当我运行上面的测试中,我得到以下异常:
AttributeError: 'TestMyApp' object has no attribute 'client'
我相信这是因为client_item()
夹具功能时在setup()
函数之前调用。
我是否正确使用灯具?或者有什么办法可以强制setup()
在夹具功能之前被调用?
在此先感谢。
答
灯具可以使用其他附着物,所以你可以用灯具一路下跌:
class TestMyApp(object):
@pytest.fixture
def client(self):
return mock_client()
@pytest.fixture
def client_item(self, client):
return client.create_item('test_item')
def test_something1(self, client_item):
# Test here.
pass
的documentation巧妙地建议过的xUnit风格的安装/拆卸方法夹具:
虽然这些安装/对于来自
unittest
或nose
背景的人来说,拆解方法很简单和熟悉,您也可以考虑使用pytest更强大的fixture mechanism,它利用了依赖注入的概念,允许使用矿石模块化和更具扩展性的管理测试状态的方法,特别是对于大型项目和功能测试。
它接着说,两种风格可以混合使用,但并不清楚其中的事情会发生的顺序。