我mock
在Python中使用时遇到了一些困难:
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
它是Mock对象,不是True
。您如何在Python的mock
库中模拟属性?
您需要使用return_value
和PropertyMock
:
with patch('requests.post') as patched_post:
type(patched_post.return_value).ok = PropertyMock(return_value=True)
这意味着:调用时requests.post
,在该调用的返回值上,PropertyMock
为属性设置a ok
以返回value True
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句