mock httpresponse
时间: 2023-09-05 16:06:42 浏览: 118
Sure, here's an example of how you can mock an HTTP response using Python's requests library:
```python
import requests
from unittest import mock
def get_response(url):
response = requests.get(url)
return response.json()
# Mocking the HTTP response
@mock.patch('requests.get')
def test_get_response(mock_get):
# Mocking the JSON response
mock_get.return_value.json.return_value = {'status': 'success', 'data': 'Hello, World!'}
# Calling the function with a mocked response
result = get_response('https://example.com/api')
# Asserting the expected values
assert result['status'] == 'success'
assert result['data'] == 'Hello, World!'
# Running the test
test_get_response()
```
In this example, we are using the `mock.patch` decorator to mock the `requests.get` method. Within the test function, we then mock the JSON response by setting the `json.return_value` attribute to our desired response. Finally, we call the `get_response` function and verify that it returns the expected JSON data.
阅读全文