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

Python async测试场景下patch修饰器mock静态方法不生效问题

Python异步测试中patch静态方法失效问题解决方案

根因分析

  • 标准unittest.mock.patch装饰器未适配异步测试方法,其生命周期与async函数的调度逻辑不匹配,测试函数执行时patch已经提前还原,因此无法拦截目标方法调用。
  • 你当前使用的patch路径B.OT._func符合patch规则(哪里调用patch哪里),同步场景下可正常运行,路径无需调整。

解决方案

方案1:使用asynctest自带的patch实现

asynctest的patch原生支持异步测试方法,直接替换导入源即可,原有代码逻辑无需修改:

# 文件A修改导入语句
import B
from asynctest import patch # 替换原unittest.mock.patch导入
from unittest import mock
import asynctest
import unittest

class Test(asynctest.TestCase):
    @patch('B.OT._func')
    async def test(self, mock_func):
        mock_func.return_value = mock.MagicMock()
        await B.foo()
        mock_func.assert_called_once()
if __name__ == '__main__':
    unittest.main()

方案2:使用patch上下文管理器

该方案可以手动控制patch的生效范围,适配所有场景,也就是你当前在用的临时解决方案:

async def test(self):
    with patch('B.OT._func') as mock_func:
        mock_func.return_value = mock.MagicMock()
        await B.foo()
        mock_func.assert_called_once()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:57:03