You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Mock实例的方法抛出异常以触发代码中的except分支?

Troubleshooting Mocking External Service Exceptions in Your Test

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.verify instead of email_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_value Instead of side_effect: Writing mock_verify.return_value = Exception(...) just returns an Exception object—it doesn’t throw it. side_effect is what tells the mock to raise the exception when called.
  • Mismatched Exception Types: If your function catches a specific exception (e.g., ExternalServiceError instead of generic Exception), you need to throw that exact type, not a generic Exception. Double-check your except clause!

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:37:46