Bird
0
0

What is wrong with this test code that tries to mock an external API call?

medium📝 Debug Q14 of 15
Django - Testing Django Applications
What is wrong with this test code that tries to mock an external API call?
from unittest.mock import patch

def test_api_call():
    with patch('myapp.services.external_api_call') as mock_call:
        mock_call.return_value = {'success': True}
    result = external_api_call()
    print(result)
Aexternal_api_call cannot be patched with patch()
BThe patch context ends before calling external_api_call
Cmock_call.return_value should be set after calling external_api_call
DMissing import for external_api_call
Step-by-Step Solution
Solution:
  1. Step 1: Check patch context usage

    The patch is applied only inside the with block, but external_api_call is called after it ends.
  2. Step 2: Understand effect on mocking

    Since external_api_call is called outside the patch block, it is not mocked and runs the real function.
  3. Final Answer:

    The patch context ends before calling external_api_call -> Option B
  4. Quick Check:

    Call must be inside patch block = C [OK]
Quick Trick: Call mocked function inside patch block or decorator [OK]
Common Mistakes:
MISTAKES
  • Calling function outside patch context
  • Setting return_value too late
  • Assuming patch works globally without context

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes