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

Python中如何Mock跨模块类?无需修改原业务代码

解决unittest.mock.patch Mock失效问题

问题核心原因:
file2.py通过from file1 import MyClass导入时,会将MyClass的直接引用存入file2自身的命名空间,后续file2中使用的MyClass是这个本地引用,而非动态指向file1.MyClass。此时patch file1.MyClass不会影响file2里已经加载的原类引用,导致Mock失效。

正确解决方案:
直接patch file2模块中的MyClass,替换file2命名空间里的那个本地引用,这样file2中实例化的就是Mock对象,原类构造函数不会执行。

test.py修改示例:

from unittest.mock import patch, MagicMock
import file2

def test_myclass_instantiation():
    # 关键:patch目标是file2.MyClass而非file1.MyClass
    with patch('file2.MyClass') as mock_myclass:
        # 自定义Mock实例的行为(可选)
        mock_instance = MagicMock()
        mock_myclass.return_value = mock_instance
        
        # 调用file2中实例化MyClass的代码(假设file2有对应逻辑)
        file2.create_myclass()
        
        # 验证Mock是否被正确调用
        mock_myclass.assert_called_once()
        # 如果实例有方法调用,可按需验证
        # mock_instance.some_method.assert_called_with('expected_param')

内容的提问来源于stack exchange,提问作者Adrian.C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 01:09:26