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

Mock带参数的类时遭遇NameError: name 'my_position' is not defined错误的解决方案咨询

Mock带参数的类时遭遇NameError: name 'my_position' is not defined错误的解决方案咨询

我最近在尝试mock一个被函数调用/初始化的类,但遇到了一个棘手的问题,想请教大家怎么解决。

我的业务代码和测试代码大概是这样的:

def example_function():
    example_class = SomeClass(my_position, num_list, suit_list)


@mock.patch('.../SomeClass')
def test_example_function(mock_SomeClass):
    example_function()

当我运行这个测试时,直接抛出了错误:

NameError: name 'my_position' is not defined

但我确认SomeClass已经被mock成功了——我在example_class = SomeClass(...)这行的上方加了断点,打印SomeClass的时候,输出是:

<MagicMock name='ShouldWePlayThisPreFlopHand' id='139711184614096'>

补充一点背景信息:my_position是example_function()所在Python包内定义的全局变量,在运行单元测试时,这个变量并没有被初始化/赋值。

有没有大佬能指点下我该怎么解决这个问题呀?

备注:内容来源于stack exchange,提问作者killerbee88

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:49:32