我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
. 你如何模拟 Pythonmock
库中的属性?