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.patch to 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
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.