Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A unit test can be conducted using a mock object by following these steps:

  1. Identify the dependencies of the method or function being tested.
  2. Create dummy objects or mock objects to replace the dependencies.
  3. Set expectations or behavior for the mock objects to simulate the actual dependencies.
  4. Call the method or function being tested and pass the mock objects as parameters.
  5. Assert the expected results against the method or function being tested.
  6. Verify that the expectations or behavior set on the mock objects were met.

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