我正在编写一个unittest类来确保方法测试成功,然后测试一个Exception。我传递的响应应该触发异常,但在测试方法中它不会被引发。值得注意的是,我可以在实际方法中手动设置异常。
测试类:
serializer = Web2TypeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
正如我所说,这很奇怪,因为我可以在实际方法中手动触发500状态代码,并且它可以提升。我甚至可以将初始模拟响应成功更改为错误,并且它将在实际方法中提升。为什么不在单位测试中加注?
正在测试的方法:
class TestAPI(TestCase):
def test_send_method(self):
with mock.patch('requests.post') as mock_request:
mock_response = mock.Mock()
mock_response.json.return_value = {
"success": "true"
}
mock_request.return_value = mock_response
send_method() // THIS WORKS NICELY
# Test that errors from the API are handled correctly.
with self.assertRaises(SendException):
mock_response.status_code = 500
mock_response.json.return_value = {
'errors': 'An error has occurred.',
}
send_method() // THIS RAISES NO EXCEPTION