1 | initial version |
A unit test can be conducted using a mock object by following these steps:
For example, let's say we have a method that calls an external API to fetch some data. We can create a mock object to simulate the API call and return a pre-defined data set. We can then test the functionality of our method without actually calling the external API.
import requests
from unittest.mock import MagicMock
def get_data_from_api():
response = requests.get('https://example.com/api/data')
return response.json()
def test_get_data_from_api():
mock_response = {'data': 'mocked data'}
requests.get = MagicMock(return_value=MockResponse(mock_response))
result = get_data_from_api()
assert result == mock_response
requests.get.assert_called_once_with('https://example.com/api/data')
class MockResponse:
def __init__(self, json_data, response_code=200):
self.json_data = json_data
self.status_code = response_code
def json(self):
return self.json_data