Pytest 模拟补丁 Attribute:Error 'function' 对象没有属性 'patch'
Pytest mocker patch Attribute:Error 'function' object has no attribute 'patch'
我正在尝试模拟我使用 mocker.patch.object 创建的另一个方法。但是我得到了 AttributeError。刚开始使用 mocker,但还没有看到可以帮助解决这种情况的示例。
尝试了从 mocker 调用方法的不同方式。
在 tests/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)
在project/services
之内
class ClassApi:
def method_to_mock(self, input1):
...
return result
AttributeError: 'function' 对象没有属性 'patch'
我对 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)
pytest 在 运行 时自动向测试函数提供参数模拟器,因此无需导入它。
我正在尝试模拟我使用 mocker.patch.object 创建的另一个方法。但是我得到了 AttributeError。刚开始使用 mocker,但还没有看到可以帮助解决这种情况的示例。
尝试了从 mocker 调用方法的不同方式。
在 tests/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)
在project/services
之内class ClassApi:
def method_to_mock(self, input1):
...
return result
AttributeError: 'function' 对象没有属性 'patch'
我对 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)
pytest 在 运行 时自动向测试函数提供参数模拟器,因此无需导入它。