Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 10 · Django Testing & Debugging
Interview question

How do you mock external API calls in Django tests? Django टेस्ट में बाहरी API कॉल्स को कैसे मॉक करें?

Answer

Tests that call a real external API during a test run are slow, flaky (network issues, rate limits), and non-deterministic, so external calls should be replaced with mocks that return controlled, predictable responses. Python's built-in unittest.mock.patch replaces the function or method making the external call for the duration of the test.

For libraries like requests, responses or requests-mock are commonly used to intercept and stub HTTP calls at the transport level, verifying both that the correct request was made and that the code correctly handles the mocked response, including error cases like timeouts or 500 responses that would be hard to trigger against a real API.

from unittest.mock import patch

class PaymentServiceTest(TestCase):
    @patch('payments.services.requests.post')
    def test_charge_success(self, mock_post):
        mock_post.return_value.status_code = 200
        mock_post.return_value.json.return_value = {"status": "success"}

        result = PaymentService().charge(amount=100)
        self.assertTrue(result.success)

टेस्ट रन के दौरान वास्तविक बाहरी API को कॉल करने वाले टेस्ट धीमे, अस्थिर और अनिश्चित होते हैं, इसलिए बाहरी कॉल्स को नियंत्रित, अनुमानित रिस्पॉन्स लौटाने वाले मॉक्स से बदला जाना चाहिए। Python का बिल्ट-इन unittest.mock.patch टेस्ट की अवधि के लिए बाहरी कॉल करने वाले फंक्शन को बदल देता है।

requests जैसी लाइब्रेरीज़ के लिए, responses या requests-mock का सामान्य रूप से उपयोग होता है HTTP कॉल्स को इंटरसेप्ट और स्टब करने के लिए।

from unittest.mock import patch

class PaymentServiceTest(TestCase):
    @patch('payments.services.requests.post')
    def test_charge_success(self, mock_post):
        mock_post.return_value.status_code = 200
        result = PaymentService().charge(amount=100)
        self.assertTrue(result.success)

Was this answer clear?