在fixtu之前Pytest调用setup()

2024-05-19 01:44:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pytest单元测试中使用fixture有困难。在

我正在使用这样的测试类:

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

当我运行上述测试时,出现以下异常:

^{pr2}$

我相信这是因为client_item()fixture函数在setup()函数之前被调用。在

我使用固定装置不正确吗?或者有什么方法可以在fixture函数之前强制调用setup()?在

提前谢谢。在


Tags: 函数testselfclientreturnobjectpytestdef
1条回答
网友
1楼 · 发布于 2024-05-19 01:44:23

设备可以使用其他设备,因此可以一直使用设备:

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巧妙地推荐fixture而不是xUnit样式的setup/teardown方法:

While these setup/teardown methods are simple and familiar to those coming from a unittest or nose background, you may also consider using pytest’s more powerful fixture mechanism which leverages the concept of dependency injection, allowing for a more modular and more scalable approach for managing test state, especially for larger projects and for functional testing.

它继续说这两种风格可以混合,但不清楚事情发生的顺序。在

相关问题 更多 >

    热门问题