我试图用pytest-mock来模拟一个类方法。下面的代码位于一个文件中,当测试运行时,我在patch函数中获得了patch。怎样才能做到这一点?
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'发布于 2022-01-13 01:58:23
在您的情况下,由于您正在修补测试文件本身中存在的类,所以可以使用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 ===============================https://stackoverflow.com/questions/70688948
复制相似问题