在Python中使用mock
相当困难:
def method_under_test():
r = requests.post("http://localhost/post")
print r.ok # prints "<MagicMock name='post().ok' id='11111111'>"
if r.ok:
return StartResult()
else:
raise Exception()
class MethodUnderTestTest(TestCase):
def test_method_under_test(self):
with patch('requests.post') as patched_post:
patched_post.return_value.ok = True
result = method_under_test()
self.assertEqual(type(result), StartResult,
"Failed to return a StartResult.")
测试实际上返回正确的值,但是r.ok
是一个模拟对象,而不是True
。如何模拟Python的mock
库中的属性?
模拟版本“1.0.1”支持问题中提到的更简单的语法,并按原样工作!
示例代码已更新(使用py.test而不是unittest):
运行此代码时使用:(确保安装了pytest)
一种简洁的方法是使用
new_callable
patch
的属性来强制patch
使用PropertyMock
,而不是MagicMock
来创建模拟对象。传递给patch
的其他参数将用于创建PropertyMock
对象。您需要使用^{} 和^{} :
这意味着:调用
requests.post
时,在该调用的返回值上,为属性ok
设置PropertyMock
,以返回值True
。相关问题 更多 >
编程相关推荐