使用模拟补丁来模拟实例方法
我试图在使用富有想象力的名称 模拟测试库测试 Django 应用程序时模拟某些内容。我似乎无法完全让它工作,我正在尝试这样做:
models.py
from somelib import FooClass
class Promotion(models.Model):
foo = models.ForeignKey(FooClass)
def bar(self):
print "Do something I don't want!"
test.py
class ViewsDoSomething(TestCase):
view = 'my_app.views.do_something'
def test_enter_promotion(self):
@patch.object(my_app.models.FooClass, 'bar')
def fake_bar(self, mock_my_method):
print "Do something I want!"
return True
self.client.get(reverse(view))
我做错了什么?
I'm trying to mock something while testing a Django app using the imaginatively named Mock testing library. I can't seem to quite get it to work, I'm trying to do this:
models.py
from somelib import FooClass
class Promotion(models.Model):
foo = models.ForeignKey(FooClass)
def bar(self):
print "Do something I don't want!"
test.py
class ViewsDoSomething(TestCase):
view = 'my_app.views.do_something'
def test_enter_promotion(self):
@patch.object(my_app.models.FooClass, 'bar')
def fake_bar(self, mock_my_method):
print "Do something I want!"
return True
self.client.get(reverse(view))
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要添加到 Kit 的答案中,指定
patch.object()
的第三个参数允许指定模拟对象/方法。否则,将使用默认的 MagicMock 对象。请注意,如果您将模拟对象指定为第三个参数,则默认的
MagicMock()
将不再传递到修补的对象中 - 例如不再:而是改为:
https://docs.python.org/3/library/unittest.mock.html#patch-object
To add onto Kit's answer, specifying a 3rd argument to
patch.object()
allows the mocked object/method to be specified. Otherwise, a defaultMagicMock
object is used.Note that, if you specify the mocking object as a third argument, then the default
MagicMock()
is no longer passed into the patched object -- e.g. no longer:but instead:
https://docs.python.org/3/library/unittest.mock.html#patch-object
啊,我对在哪里应用补丁装饰器感到困惑。固定的:
Ah I was confused on where to apply that patch decorator. Fixed:
如果您愿意
assert_known
等针对模拟方法,使用patch.object
并将替换方法包装在MagicMock(side_effect=)
中,即:例如:
If you'd like to do
assert_called
etc. against the mocked method, use thepatch.object
and wrap replacement method in aMagicMock(side_effect=)
, ie:eg.: