如何让Mock实例的方法抛出异常以触发代码中的except分支?
Let’s walk through how to fix this—getting exceptions to trigger in mocked external calls is super common, but it’s easy to trip up on small details like mock paths or how you define the exception.
First, let’s start with a quick example of what your code might look like (since you didn’t share the exact snippet, I’ll use a typical setup):
Example Original Function
Suppose your function lives in email_processor.py:
import external def handle_email_verification(email): try: verification_result = external.verify(email) return f"Success: {verification_result}" except Exception as err: return f"Failed: {str(err)}"
Correct Mocking to Trigger Exceptions
The key here is making sure you’re mocking the right reference to external.verify and using side_effect to throw the exception (not return_value).
Using unittest.mock (Built-in)
from unittest.mock import patch from email_processor import handle_email_verification def test_verification_failure(): # Critical: Patch the reference that your function actually uses! # This is the most common mistake—don't patch "external.verify" directly. with patch("email_processor.external.verify") as mock_verify: # Tell the mock to raise an exception when called mock_verify.side_effect = Exception("External service timed out") # Call your function result = handle_email_verification("user@test.com") # Verify the except branch was triggered assert result == "Failed: External service timed out" # Verify the mock was called exactly once with the right email mock_verify.assert_called_once_with("user@test.com")
Using pytest-mock (If You Use Pytest)
If you’re using pytest with the pytest-mock plugin, the approach is similar but cleaner:
def test_verification_failure(mocker): # Again, target the reference in your function's module mock_verify = mocker.patch("email_processor.external.verify") mock_verify.side_effect = Exception("Service unavailable") result = handle_email_verification("user@test.com") assert "Failed:" in result mock_verify.assert_called_once_with("user@test.com")
Common Mistakes That Break Your Mock
- Wrong Mock Path: If you patch
external.verifyinstead ofemail_processor.external.verify, Python will mock the module-level reference in your test file, not the one your function is using. This is the #1 reason mocks don’t trigger as expected. - Using
return_valueInstead ofside_effect: Writingmock_verify.return_value = Exception(...)just returns an Exception object—it doesn’t throw it.side_effectis what tells the mock to raise the exception when called. - Mismatched Exception Types: If your function catches a specific exception (e.g.,
ExternalServiceErrorinstead of genericException), you need to throw that exact type, not a generic Exception. Double-check yourexceptclause!
Quick Debugging Tip
If you’re still stuck, add print(mock_verify.call_count) right after calling your function. If it returns 0, your mock path is definitely wrong—you’re not patching the reference the function is actually invoking.
内容的提问来源于stack exchange,提问作者Ahasanul Haque

