【发布时间】:2020-10-23 11:18:11
【问题描述】:
我想用 Pytest 测试异常。我发送一个 HTTP 请求并得到响应。我希望响应损坏,因此 response.json() 转到 except 块。以下是示例。
发送请求,接收响应:
def send_message_json():
# ...
try:
response = cls.send_message(method, url, **kwargs)
if response:
return response.json() # this is what should fail
except simplejson.errors.JSONDecodeError as err:
raise err # this is to be achieved
单元测试应该断言应该引发 simplejson.errors.JSONDecodeError。
@mock.patch.object(Service, 'send_message_json')
def test_send_message_json_exception(mock_send):
svc = Service()
with pytest.raises(simplejson.errors.JSONDecodeError): # this should assert the exceptions was raised
svc.send_message_json("GET", 'http://my.url/')
我无法激活 pytest.mock.object 引发的异常。什么会使 .json() 在模拟中失败?
【问题讨论】:
-
@mock.patch.object(Service, 'send_message_json', side_effect=JSONDecodeError) -
@hoefling 使用这种方法我在想,无论我对函数做了什么更改,它都会抛出这个错误。因此,例如,如果我对这个不应该通过的方法 send_message_json() 进行更改,side_effect 是否仍然会抛出一个不会抛出的错误??
标签: python unit-testing exception mocking pytest