Ask Your Question
1

How can a unit test be conducted using a mock object?

asked 2023-07-19 03:03:18 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-19 03:27:01 +0000

scrum gravatar image

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
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-19 03:03:18 +0000

Seen: 11 times

Last updated: Jul 19 '23