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

测试含多异步调用的异步函数:如何正确Mock异步调用?

解决异步函数Mock返回值异常的问题

问题核心

你遇到的问题要么是patch的路径不正确,要么是对AsyncMock的返回值设置逻辑理解有误,导致被测试代码中调用的another_func未被正确Mock,返回了原始Mock对象而非预期的整数1。

解决方案

1. 修正Patch路径(最常见原因)

确保你patch的是被测试代码中实际引用another_func的模块路径,而非原函数的定义路径。举个例子:

  • 若被测试的post函数在api.py中,代码里写的是from utils import another_func
  • 那么patch路径必须是api.another_func,而非utils.another_func
  • 因为Python导入时会在api模块中创建指向another_func的本地引用,只有patch这个本地引用才能生效

2. 正确设置AsyncMock返回值

如果路径正确仍有问题,用以下方式确保返回值设置生效:

import asyncio
import json
from unittest import mock

async def test_the_call(self, mock_another_func):
    exp_res = {"status": "success"}  # 预期的JSON结果

    # 方式1:直接设置return_value(AsyncMock会自动包装为可等待对象)
    mock_another_func.return_value = 1

    # 方式2:用Future手动包装(兼容旧版本Python)
    # future = asyncio.Future()
    # future.set_result(1)
    # mock_another_func.return_value = future

    body, _, _ = await self.post(self.path, body=json.dumps(self.body))
    response = json.loads(body)
    assert response == exp_res

3. 验证Mock是否被正确调用

可以在测试中加入断言,确认Mock确实被触发,彻底排除路径错误的可能:

# 在调用post方法之后添加
mock_another_func.assert_called_once_with(x, y)  # 替换成实际传入的参数x和y

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:02:45