我在 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
是一个 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
时,在该调用的返回值上,为属性 ok
设置一个 PropertyMock
以返回值 True
。
关于python - Python模拟中的模拟属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16867509/