我正在尝试使用模拟修补类方法in the documentation。 Mock对象本身工作正常,但它的方法不能:例如,即使call_count
类对象的method_calls
属性,它们的属性如Mock
也不会更新。更重要的是,他们的return_value
属性会被忽略:
class Lib:
"""In my actual program, a module that I import"""
def method(self):
return "real"
class User:
"""The class I want to test"""
def run(self):
l = Lib()
return l.method()
with patch("__main__.Lib") as mock:
#mock.return_value = "bla" # This works
mock.method.return_value = "mock"
u = User()
print(u.run())
>>>
mock
<MagicMock name='Lib().method()' id='39868624'>
我在这里做错了什么?
编辑:通过构造函数传递类Mock
也不起作用,因此这与patch
函数无关。
答案 0 :(得分:16)
我发现了我的错误:为了配置我的模拟实例的方法,我必须使用mock().method
而不是mock.method
。
class Lib:
"""In my actual program, a module that I import"""
def method(self):
return "real"
class User:
"""The class I want to test"""
def run(self):
l = Lib()
return l.method()
with patch("__main__.Lib") as mock:
#mock.return_value = "bla" # This works
mock().method.return_value = "mock"
u = User()
print(u.run())
答案 1 :(得分:1)
from mock import *
class Lib:
"""In my actual program, a module that I import"""
def method(self):
return "real"
class User:
"""The class I want to test"""
def run(self, m):
return m.method()
with patch("__main__.Lib") as mock:
#mock.return_value = "bla" # This works
mock.method.return_value = "mock"
print User().run(mock)
答案 2 :(得分:1)
我模仿这样的类方法:
def raiser(*args, **kwargs):
raise forms.ValidationError('foo')
with mock.patch.object(mylib.Commands, 'my_class_method', classmethod(raiser)):
response=self.admin_client.get(url, data=dict(term='+1000'))