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

单元测试中如何正确Mock类?解决Presentation类Mock失败问题

正确Mock外部类的解决方案

你的问题出在patch的目标路径错误,unittest.mock.patch需要替换的是被测代码(MyClass)所在模块中实际引用的Presentation对象,而非原pptx模块中的类定义。

问题根源

当你在MyClass所在模块执行from pptx import Presentation时,该模块会生成一个指向pptx.Presentation的本地引用。你当前patch的是原模块的pptx.Presentation,但MyClass调用的是本地模块内的这个引用,所以mock没有生效,仍执行了真实的Presentation初始化逻辑,导致抛出文件找不到的错误。

修改后的代码示例

假设MyClass定义在my_module.py中:

# my_module.py
from pptx import Presentation
class MyClass:
    def __init__(self, path:str):
        self.path = path
        self.pres = Presentation(path)

测试文件中需要patchmy_module.Presentation(即MyClass所在模块的本地引用):

# test_myclass.py
from unittest.mock import patch
from my_module import MyClass

@patch("my_module.Presentation")
def test_init(mock_presentation):
    MyClass(path="path")
    # 可选:添加断言验证mock是否被正确调用
    mock_presentation.assert_called_once_with("path")

核心规则

使用patch时,目标路径必须是被测代码实际使用对象的引用位置:

  • 如果被测代码用import pptx然后pptx.Presentation调用,就patch"my_module.pptx.Presentation"
  • 如果被测代码用from pptx import Presentation调用,就patch"my_module.Presentation"

内容的提问来源于stack exchange,提问作者Roma V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:38:13