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

使用python-mockito无法Mock跨文件调用的函数问题

解决python-mockito无法Mock函数的问题

问题原因

核心问题是模块导入方式导致的引用不一致:

  • build_config.py中使用from read_report_config import *,会将read_gsheet_config函数直接复制到build_config模块的命名空间中,形成一个独立的本地引用。
  • 测试代码里when(read_report_config).read_gsheet_config(...)只Mock了read_report_config模块中的原函数,但build_config里调用的是本地复制的引用,不会被这个Mock影响,因此实际函数仍会执行。

解决办法

方法1:修改原代码的导入方式

调整build_config.py的导入逻辑,通过模块引用调用函数,确保Mock能作用到调用链:

# build_config.py
import read_report_config

def config_builder(*some_parameters*):
    ...
    new_enabled_list = read_report_config.read_gsheet_config(logging, "Some sheet name", config_dir, data)
    ...
    return config_data

方法2:Mock目标模块中的引用(无需修改业务代码)

如果不想改动原业务代码,直接在测试中Mockbuild_config模块内的read_gsheet_config引用:

# test_build_config.py
from unittest import TestCase
from mockito import when, verifyStubbedInvocationsAreUsed
from src import build_config

class SimpleMockitoTest(TestCase):
    def test_build_config(self):
        new_enabled_list = ['hello', 'something', 'it', 'is']
        # Mock build_config模块内的read_gsheet_config引用
        when(build_config).read_gsheet_config(...).thenReturn(new_enabled_list)
        config_data = build_config.config_builder(*some_parameters*)
        # 可选:验证Mock被正确调用
        verifyStubbedInvocationsAreUsed()

if __name__ == '__main__':
    import unittest
    unittest.main()

额外注意:测试中when语句的参数需要匹配调用时的实际参数,若不确定具体参数,可使用any()通配符(如when(build_config).read_gsheet_config(any(), any(), any(), any()).thenReturn(...)),参数不匹配也会导致Mock不生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:40:34