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

如何在测试时mock另一个类方法中的helper_method?

问题描述

需要测试notifier文件中的notify方法,该方法调用了Class_A的another_class_method方法。Class_A的定义如下:

def notify():
    Class_A.another_class_method()

class Class_A:
    @classmethod
    def prepare(cls):
        helper_method()

    @classmethod
    def another_class_method(cls):
        cls.prepare()

注:原代码存在语法小问题,已修正(类名统一为Class_A,类方法添加cls参数,another_class_method改为类方法以调用prepare)

尝试mock其中的helper_method,使用如下patch方式未成功:

with patch(
    'notifier.notify.Class_A.another_class_method.prepare.helper_method',
    return_value=True
):
    # 测试逻辑
正确的Mock实现方式
  • 核心原则:Mock要针对helper_method被调用时的实际引用路径
    Python的unittest.mock.patch是基于模块导入的引用生效的,你需要明确helper_method在哪个模块被定义,以及Class_A.prepare实际调用的是哪个模块中的helper_method。

  • 情况1:helper_method与Class_A在同一模块(如notifier.py)
    直接patch当前模块中的helper_method即可,因为prepare调用的是本地模块的该函数:

    from unittest.mock import patch
    from notifier import notify, helper_method
    
    def test_notify():
        with patch('notifier.helper_method', return_value=True):
            notify()
            # 验证helper_method被调用一次
            helper_method.assert_called_once()
    
  • 情况2:helper_method来自其他模块(如utils.py)
    如果notifier.py中是通过from utils import helper_method导入的,那么需要patch的是notifier模块中导入的那个引用,而非原模块的helper_method:

    from unittest.mock import patch
    from notifier import notify
    
    def test_notify():
        with patch('notifier.helper_method', return_value=True):
            notify()
            # 验证调用
            notifier.helper_method.assert_called_once()
    
  • 错误原因说明
    你之前写的嵌套路径完全错误,helper_method并不是prepare方法的属性,而是一个独立函数,prepare只是调用它而已,不存在...prepare.helper_method这样的路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:45:03