相关疑难解决方法(0)

Python模拟中的Mock属性?

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.")
Run Code Online (Sandbox Code Playgroud)

测试实际上返回正确的值,但是r.ok是Mock对象,而不是True.你如何在Python的mock库中模拟属性?

python testing unit-testing mocking python-mock

63
推荐指数
3
解决办法
5万
查看次数

标签 统计

mocking ×1

python ×1

python-mock ×1

testing ×1

unit-testing ×1