Mocking in Django Tests
A snippet showing how to use mocks in Django tests.
# models.py
from django.db import models
class Report(models.Model):
title = models.CharField(max_length=100)
# admin.py
from django.contrib import admin
from .models import Report
@admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
list_display = ("title",)
# tests/test_mocking.py
from django.test import TestCase
from unittest.mock import patch
from .services import send_to_external
class MockingTest(TestCase):
@patch("app.services.send_to_external")
def test_external_call_mocked(self, mocked):
mocked.return_value = {"ok": True}
res = send_to_external({"id": 1})
self.assertTrue(res["ok"])
mocked.assert_called_once()
Explanation:
-
Use
unittest.mock.patchto replace external calls with fakes. - Patch by import path used by the system under test (SUT).
- Category Testing
- Total Views 583
- Last Modified 25 March, 2026
- Tags #testing #mocking #unittest #python
Previous snippet
Testing Async Views
Next snippet