[英]Mocking class method with pytest-mock returns error
我正在尝试使用 pytest-mock 模拟 class 方法。 我在一个文件中有下面的代码,当测试运行时,我在patch
function 中得到ModuleNotFoundError: No module named 'RealClass'
。 如何使这项工作?
class RealClass:
def some_function():
return 'real'
def function_to_test():
x = RealClass()
return x.some_function()
def test_the_function(mocker):
mock_function = mocker.patch('RealClass.some_function')
mock_function.return_value = 'mocked'
ret = function_to_test()
assert ret == 'mocked'
在您的情况下,由于您正在修补测试文件本身中存在的 class ,因此您将使用mocker.patch.object
。
mock_function = mocker.patch.object(RealClass, 'some_function')
collected 1 item
tests/test_grab.py::test_the_function PASSED [100%]
============================== 1 passed in 0.03s ===============================
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.