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

如何用模拟数据测试YouTube Data API的直播捐赠查询接口?

测试YouTube Data API直播捐赠接口的模拟数据方案

1. 手动构造符合API格式的模拟响应

先参照YouTube Data API官方文档中liveChatMessages接口的响应结构(捐赠记录属于superChatEvent类型),手动生成假数据。示例JSON结构如下:

{
  "items": [
    {
      "id": "mock-superchat-1",
      "snippet": {
        "type": "superChatEvent",
        "liveChatId": "mock-live-chat-id",
        "authorChannelId": "UC123456789",
        "displayMessage": "感谢主播!",
        "superChatDetails": {
          "amountMicros": "5000000",
          "currency": "USD",
          "amountDisplayString": "$5.00",
          "userComment": "加油!"
        },
        "publishedAt": "2024-05-20T12:34:56Z"
      }
    },
    {
      "id": "mock-superchat-2",
      "snippet": {
        "type": "superChatEvent",
        "liveChatId": "mock-live-chat-id",
        "authorChannelId": "UC987654321",
        "displayMessage": "支持一波",
        "superChatDetails": {
          "amountMicros": "10000000",
          "currency": "EUR",
          "amountDisplayString": "€10.00",
          "userComment": "很棒的直播"
        },
        "publishedAt": "2024-05-20T12:35:10Z"
      }
    }
  ],
  "pageInfo": {
    "totalResults": 2,
    "resultsPerPage": 2
  }
}

在代码里直接返回这个JSON对象,替代真实的API调用结果,即可测试你的数据处理逻辑。

2. 使用Mock工具拦截API请求

如果代码直接调用API接口,可用Mock工具拦截请求并返回模拟数据:

  • Python:用unittest.mock的patch装饰器替换HTTP库的返回值:
from unittest.mock import patch, Mock
import requests

def test_get_donations():
    mock_response = Mock()
    mock_response.json.return_value = {
        "items": [
            # 填入上述模拟数据
        ]
    }
    mock_response.status_code = 200

    with patch('requests.get', return_value=mock_response):
        # 调用你的捐赠记录获取函数
        donations = your_get_donations_function()
        # 断言处理结果符合预期
        assert len(donations) == 2
  • JavaScript/TypeScript:用Jest拦截Axios或fetch请求:
import axios from 'axios';
jest.mock('axios');

test('fetch donations correctly', async () => {
    const mockData = {
        "items": [
            // 填入上述模拟数据
        ]
    };
    axios.get.mockResolvedValue({ data: mockData });

    const donations = await yourDonationFetchFunction();
    expect(donations.length).toBe(2);
});

3. 利用YouTube测试直播环境

创建一个未公开的测试直播(无需真实开播或观众),获取其liveChatId后,可通过liveChatMessages.insert接口发送模拟的superChatEvent事件(需授权,但不会产生真实交易),之后用你的目标接口即可获取到这些测试数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:05:16