【发布时间】:2015-09-06 01:51:20
【问题描述】:
我最近注意到,如果我使用mock.patch 模拟一个方法,它不会在call_args 字段中列出传递给模拟方法的实例对象。这是设计使然吗?下面的代码/输出可能更好地解释我的意思:
#!/usr/bin/env python2
from mock import patch
class Dog(object):
def bark(self):
print("Woof woof!")
Dog().bark()
def new_method(*args):
print("args = %s" % str(args))
Dog.bark = new_method
Dog().bark()
with patch.object(Dog, "bark"):
d = Dog()
d.bark()
print("d.bark was called: %s" % str(d.bark.called))
print("d.bark was called with args/kwargs: %s" % str(d.bark.call_args))
输出是:
Woof woof!
args = (<__main__.Dog object at 0x7f42c2dbc3d0>,)
# Mocking bit
d.bark was called: True
d.bark was called with args/kwargs: ((), {})
您可以看到实例对象在替换bark 时被传递给new_method。但是您在模拟方法的call_args 中看不到它。这不是很奇怪吗?我正在使用 1.01 版的 python 模拟库。
【问题讨论】:
标签: python unit-testing mocking