Pytest mocker 补丁属性:错误“函数”对象没有属性“补丁”

bra*_*999 3 python api-design pytest

我正在尝试模拟我使用 mocker.patch.object 创建的另一种方法。但是我得到了 AttributeError。使用 mocker 的新手,但还没有看到可以帮助解决这种情况的示例。

尝试了从 mocker 调用该方法的不同方式。

在测试/test_unit.py

from pytest_mock import mocker

class TestApp:

 def setup_method(self):
        self.obj = ClassApi()

 def test_class_api_method(self, client):

        return_value = {'name': 'test'}
        mocker.patch.object(self.obj, 'method_to_mock')
        mocker.result(return_value)
Run Code Online (Sandbox Code Playgroud)

在项目/服务中

class ClassApi:

       def method_to_mock(self, input1):
         ...
        return result
Run Code Online (Sandbox Code Playgroud)

AttributeError: 'function' 对象没有属性 'patch'

pyp*_*ypy 9

我对 Pytest-Mock 不是很熟悉,但基于对您应该mocker用作夹具的文档的查看。所以你的函数应该是这样的:

 def test_class_api_method(self, client, mocker):

        return_value = {'name': 'test'}
        mocker.patch.object(self.obj, 'method_to_mock')
        mocker.result(return_value)
Run Code Online (Sandbox Code Playgroud)

pytest 在运行时自动向测试函数提供参数模拟器,因此无需导入它。