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

Python单元测试中如何Patch类初始化的返回值?

问题描述

我正尝试在单元测试中将初始化对象的值覆盖为预设值,使用mock库搭配pytest。以下是演示问题的代码:

def function_to_test():
    new_object = Object(arg1, arg2, arg3)

    return func1(new_object)

我希望测试该对象是否以arg1、arg2、arg3完成初始化,同时需要Patch new_object的值,以此测试func1是否被传入指定参数。当前测试代码如下:

def test_function_to_test(mocker):
    mocker.patch(Object.__init__, return_value=None)
    mocker.patch(func1)

    function_to_test()
    
    Object.__init__.assert_called_once_with(arg1, arg2, arg3)
    
    mock_object = "test"

    func1.assert_called_once_with(mock_object) # this line fails

最后一行断言失败,因为需要将new_object的值Patch为预设值。尝试修改初始化方法的return_value,但__init__函数无返回值导致报错,请问如何让Object的初始化返回预定义值?

解决方案

Python 中 __init__ 强制要求返回 None,因此无法通过修改它的返回值实现需求。正确思路是直接 Patch 整个 Object 类,让它返回预设对象,同时验证类的调用参数(即初始化参数):

修改后的测试代码

def test_function_to_test(mocker):
    # 定义要传入func1的预设对象
    mock_object = "test"
    # Patch Object类,指定实例化后返回预设对象
    mock_obj_cls = mocker.patch("your_module.Object")  # 替换为Object实际所在模块路径
    mock_obj_cls.return_value = mock_object
    # Patch func1
    mock_func1 = mocker.patch("your_module.func1")  # 替换为func1实际所在模块路径

    # 执行待测试函数
    function_to_test()

    # 验证Object初始化参数正确
    mock_obj_cls.assert_called_once_with(arg1, arg2, arg3)
    # 验证func1被传入预设对象
    mock_func1.assert_called_once_with(mock_object)

核心逻辑说明

  • Patch 整个类时,调用 Object(arg1, arg2, arg3) 等价于调用 mock 类的 __call__ 方法,此时用 assert_called_once_with 验证参数,就等同于验证 __init__ 的入参(类实例化时的参数会传递给 __init__ 的 self 之外的参数)。
  • 通过 mock_obj_cls.return_value 指定类实例化后的返回值,这样待测试函数中的 new_object 就会被替换为预设的 mock_object,从而满足 func1 的参数断言要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:07:20