0
0
Djangoframework~5 mins

Mocking external services in Django

Choose your learning style9 modes available
Introduction

Mocking external services helps you test your Django app without calling real outside systems. This makes tests faster and safer.

When your app calls an API to get data and you want to test without using the real API.
When you want to simulate different responses from an external service to see how your app reacts.
When the external service is slow or unreliable and you want your tests to run quickly.
When you want to avoid using real credentials or sensitive data during testing.
Syntax
Django
from unittest.mock import patch

@patch('path.to.external.service.function')
def test_function(mock_function):
    mock_function.return_value = 'mocked response'
    # your test code here

Use @patch to replace the real function with a mock during the test.

Set return_value on the mock to control what it returns.

Examples
This mocks the requests.get call to return a fake response with status 200 and a JSON body.
Django
from unittest.mock import patch

@patch('requests.get')
def test_api_call(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'key': 'value'}
    response = requests.get('http://fakeapi.com')
    assert response.status_code == 200
    assert response.json() == {'key': 'value'}
This mocks a custom send_email function to always return True during the test.
Django
from unittest.mock import patch

@patch('myapp.services.send_email')
def test_send_email(mock_send):
    mock_send.return_value = True
    result = send_email('test@example.com')
    assert result is True
Sample Program

This example shows how to mock the requests.get call inside the fetch_data function. The test replaces the real HTTP call with a mock that returns a fake JSON response. When run, it prints the mocked data.

Django
from unittest.mock import patch
import requests

def fetch_data():
    response = requests.get('https://api.example.com/data')
    if response.status_code == 200:
        return response.json()
    return None

@patch('requests.get')
def test_fetch_data(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'name': 'Test'}
    data = fetch_data()
    print(data)

if __name__ == '__main__':
    test_fetch_data()
OutputSuccess
Important Notes

Always patch the exact location where the function is used, not where it is defined.

Mocks help keep tests fast and independent from outside systems.

Summary

Mocking replaces real external calls with fake ones during tests.

Use @patch decorator from unittest.mock to mock functions.

Set return values on mocks to control test scenarios easily.