使用带有“ new”参数的mock.patch.object

时间:2019-11-28 16:48:09

标签: python python-unittest

我当前正在使用unittest和unittest.mock来测试我的代码。例如,当我想覆盖某个方法的行为时,请按以下步骤操作:

def mock_get(address):
   class Response():
       def __init__(self):
           self.status_code = 200
       def json(self):
           dict= {"key":value}
           return json.dumps(dict)
        r = Response()
        return r
with mock.patch.object(requests, 'get', new=mock_get) as get: 
    #call function that uses requests.get
    get.assert_called_with(address)#this throws an exception saying that a function() type does not have an attribute called "assert_called_with"

在此示例中,无需使用“ new”参数也可以实现相同的功能,但是在某些情况下,我想编写一个新函数来替换原始函数,但仍能够像访问您的模拟实例一样访问修补没有“ new”参数的函数,如下所示:

with mock.patch("path.to.requests.get") as get:
    get.status_code = 200
    get.json.return_value = {"test_key": "test_value"}
    # call function that uses requests.get
    get.assert_called_with(address)#this works

0 个答案:

没有答案