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

Python中使用Mockito进行方法Mock:如何Mock类外函数?

解决Mockito Mock模块级函数的问题

嘿,这个问题我之前也碰到过!要mock模块级别的函数,关键是要从函数所在的模块上下文去mock它,而不是直接引用函数本身。你之前的尝试没生效,是因为没有正确针对模块命名空间里的another_function进行mock。

问题原因

当interesting_function调用another_function()时,它实际是在调用当前模块(也就是你的脚本文件)命名空间下的another_function。如果只是直接mock函数对象,不会影响到模块内的函数调用,所以测试里的verify会失败。

解决方案

你需要从当前模块导入自己,然后mock这个模块下的another_function。假设你的代码在my_script.py文件里,具体步骤如下:

  1. 首先导入当前模块(可以用import __main__,或者如果是单独的模块文件,直接导入模块名)
  2. 使用when(模块对象).another_function()来mock这个函数
  3. 调用interesting_function()后,verify模块对象的another_function被调用

完整测试代码示例

import os
import unittest
import __main__ as my_module  # 导入当前模块
from mockito import when, verify

def interesting_function():
    os.system('mkdir some_dir')
    another_function()

def another_function():
    print('Done')

class InterestingFunctionTests(unittest.TestCase):
    def test_interesting_function(self):
        # Mock os.system
        when(os).system('mkdir some_dir').thenReturn(0)
        # Mock 当前模块的another_function
        when(my_module).another_function()
        
        interesting_function()
        
        # 验证两个函数都被调用
        verify(os).system('mkdir some_dir')
        verify(my_module).another_function()

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

如果你的代码是放在单独的模块文件(比如my_module.py)里,而测试代码在另一个文件,那只需要把import __main__ as my_module改成import my_module即可。

补充说明

  • 如果another_function没有返回值,thenReturn(None)可以省略,直接写when(my_module).another_function()就行
  • 核心思路是:要mock的是被测试函数所在上下文里的那个函数引用,而不是函数本身的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:37:55