You need to enable JavaScript to run this app. Python mock修改类属性的类方法时如何统计其调用次数
优惠活动
大模型
产品
解决方案
定价
更多

Python mock修改类属性的类方法时如何统计其调用次数

你遇到的报错是因为直接通过wraps封装自定义函数作为Mock对象时,Mock作为实例方法被调用时不会自动将实例的self参数透传给你封装的mock_step,导致参数缺失。

你可以用side_effect来实现需求,这是该场景下的标准写法,完整实现代码如下:

import time

class Example:
    def run_steps(self):
        self.steps = 0
        while self.steps < 4:
            self.step()
    
    def step(self):
        # 高开销API调用
        print("wasting time...")
        time.sleep(1000)
        self.steps += 1

def mock_step(self):
    print("skip the wasting time")
    self.steps += 1

def test_example_step_called(mocker):
    example = Example()
    # patch.object返回的就是Mock对象,将side_effect指定为自定义的mock_step
    patched_step = mocker.patch.object(Example, 'step', side_effect=mock_step)

    example.run_steps()

    # 可以正常调用Mock的所有属性和方法做断言
    assert patched_step.call_count == 4
    # 也可以验证实例属性是否正常累加
    assert example.steps == 4

原理说明

  • side_effect指定的可调用对象,会接收原方法被调用时传入的所有参数(实例方法调用时自动传入的self也会被正常透传),完全执行你自定义的模拟逻辑
  • 同时patch.object返回的Mock对象会正常统计调用次数、调用参数等所有Mock相关的信息,完全满足你既要跳过高开销逻辑、又要做调用断言的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 16:24:04