【发布时间】:2015-10-11 22:49:41
【问题描述】:
我有一个改变对象属性的对象方法。另一种方法(我正在尝试测试的方法)多次调用第一种方法,然后使用已修改的属性。如何在明确说明第一种方法如何更改该属性的同时测试第二种方法?
例如:
def method_to_test(self):
output = []
for _ in range(5):
self.other_method()
output.append(self.attribute_changed_by_other_method)
return output
我想指定attribute_changed_by_other_method 将由于other_method 而变成的一些特定值(而真正的other_method 使用概率来决定如何更改attribute_changed_by_other_method)。
我猜最好的方法是“模拟”属性attribute_changed_by_other_method,这样每次读取该值时,它都会返回我的规范的不同值。我似乎无法找到如何做到这一点。我看到的另一个选项是确保 other_method 被模拟以每次以定义的方式更新属性,但我不知道这样做的特别干净的方式。有人可以提出一种合理的解决方法吗?非常感谢。
【问题讨论】:
标签: python unit-testing python-3.x testing mocking