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
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-19 03:03:18 +0000
Seen: 11 times
Last updated: Jul 19 '23
How to provide parameters to machine learning model objects?
Is it impossible to delete any objects provided by ActiveRecord_Associations_CollectionProxy?
What is the technique for creating a mapping of an array containing various objects and values?
How can an array of objects be initialized in C# without implementing a loop?
Is it possible to retrieve objects as a list in jq in order to access them by index?
How to query an array of objects with JSONB in Postgres?
How can the clipping of objects in matplotlib 3D be modified?
In Laravel, what is the process for comparing two objects and obtaining distinct columns?