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

使用patch.object时,能否通过self断言对象的成员变量?

问题解答

当然可以做到,你可以通过两种方式在mock函数被调用时验证self.a的值为3:

方法一:利用side_effect在调用时直接断言

定义一个替代的mock函数,它会接收原成员函数的所有参数(第一个参数就是实例self),在函数内部直接对self.a做断言:

import unittest
from unittest.mock import patch

class ToBeTestedClass:
    def __init__(self):
        self.a = 3

    def to_be_tested_function(self):
        pass

def intermediary_function_expected():
    obj = ToBeTestedClass()
    obj.to_be_tested_function()

class TestToBeTestedClass(unittest.TestCase):
    def test_self_a_assert_via_side_effect(self):
        def mock_func(self):
            # 直接在mock函数内断言self的属性
            self.assertEqual(self.a, 3)

        with patch.object(ToBeTestedClass, 'to_be_tested_function', side_effect=mock_func):
            intermediary_function_expected()

方法二:调用后从mock的call_args中提取self实例断言

patch.object返回的mock对象会记录所有调用参数,成员函数的第一个位置参数就是实例self,你可以从call_args中取出这个实例后再做断言:

import unittest
from unittest.mock import patch

class ToBeTestedClass:
    def __init__(self):
        self.a = 3

    def to_be_tested_function(self):
        pass

def intermediary_function_expected():
    obj = ToBeTestedClass()
    obj.to_be_tested_function()

class TestToBeTestedClass(unittest.TestCase):
    def test_self_a_assert_via_call_args(self):
        with patch.object(ToBeTestedClass, 'to_be_tested_function') as mock_method:
            intermediary_function_expected()
            # 从call_args的位置参数中取出self实例
            self_instance = mock_method.call_args[0][0]
            self.assertEqual(self_instance.a, 3)

补充说明

你之前觉得call_args中没有self参数,是因为对call_args的结构不熟悉:它的格式为((位置参数元组), 关键字参数字典),成员函数调用时,第一个位置参数必然是实例self,所以只要从call_args[0][0]就能拿到它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:45:27