Bird
0
0

You want to test a Django view that calls an external payment API. Which approach correctly mocks the external call and verifies the view handles a failure response gracefully?

hard📝 state output Q15 of 15
Django - Testing Django Applications
You want to test a Django view that calls an external payment API. Which approach correctly mocks the external call and verifies the view handles a failure response gracefully?
from unittest.mock import patch
from django.test import Client

@patch('payments.api.call_payment')
def test_payment_failure(mock_call):
    mock_call.return_value = {'status': 'error', 'code': 500}
    client = Client()
    response = client.post('/pay/')
    print(response.status_code)
What should you add to the test to check the view's behavior?
AAssert response.status_code is 500 to confirm failure handling
BRemove patch decorator to test real API call
CAssert mock_call was called once and response.status_code is 200
DSet mock_call.return_value to None to simulate failure
Step-by-Step Solution
Solution:
  1. Step 1: Understand mocking external payment API

    The patch replaces call_payment with a mock returning an error response.
  2. Step 2: Verify view handles error but returns HTTP 200

    The view should catch the error and respond with HTTP 200 (page loads with error message), not propagate 500.
  3. Step 3: Check mock call was made

    Asserting mock_call was called confirms the external API was invoked in the view.
  4. Final Answer:

    Assert mock_call was called once and response.status_code is 200 -> Option C
  5. Quick Check:

    Mock call checked + 200 response = B [OK]
Quick Trick: Check mock call and expect view to handle errors with 200 [OK]
Common Mistakes:
MISTAKES
  • Expecting 500 status from view on API error
  • Not asserting mock call was made
  • Removing patch and making real calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes