You need to enable JavaScript to run this app. 如何使用mocha模拟@azure/event-hub生产者连接开展单元测试
优惠活动
大模型
产品
解决方案
定价
更多

如何使用mocha模拟@azure/event-hub生产者连接开展单元测试

Azure EventHub 连接Mock单元测试实现(Node.js)

你提供的原始业务代码如下:

const { EventHubProducerClient } = require("@azure/event-hubs");

const connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING";
const eventHubName = "EVENT HUB NAME";

async function main() {
  // 创建生产者客户端向事件中心发送消息
  const producer = new EventHubProducerClient(connectionString, eventHubName);

  // 准备包含3条事件的批次
  const batch = await producer.createBatch();
  batch.tryAdd({ body: "First event" });
  batch.tryAdd({ body: "Second event" });
  batch.tryAdd({ body: "Third event" });    

  // 向事件中心发送批次
  await producer.sendBatch(batch);

  // 关闭生产者客户端
  await producer.close();

  console.log("A batch of three events have been sent to the event hub");
}

main().catch((err) => {
  console.log("Error occurred: ", err);
});

注意需要在业务代码末尾导出main函数,方便测试文件引入:

module.exports = { main };

Mock实现方案(以Jest测试框架为例)

  • 核心思路是伪造@azure/event-hubs包的导出内容,重写EventHubProducerClient的所有业务用到的方法,不需要真实连接EventHub服务即可完成测试
  • 需覆盖的伪造逻辑包括:EventHubProducerClient构造函数、实例方法createBatch/sendBatch/close、批次对象的tryAdd方法

完整测试代码如下:

// 引入依赖和待测试的main函数
const { EventHubProducerClient } = require("@azure/event-hubs");
const { main } = require("./你的业务代码文件名");

// Mock整个@azure/event-hubs模块
jest.mock("@azure/event-hubs");

describe("EventHub 消息发送逻辑测试", () => {
  // 伪造批次对象的tryAdd方法
  const mockTryAdd = jest.fn();
  // 伪造批次实例
  const mockBatch = {
    tryAdd: mockTryAdd
  };

  beforeEach(() => {
    // 每次测试前清空所有mock的调用记录
    jest.clearAllMocks();
    // 给EventHubProducerClient的所有实例方法挂载mock实现
    EventHubProducerClient.mockImplementation(() => ({
      createBatch: jest.fn().mockResolvedValue(mockBatch),
      sendBatch: jest.fn().mockResolvedValue(true),
      close: jest.fn().mockResolvedValue(true)
    }));
  });

  test("应该正确创建批次、添加3条事件并完成发送", async () => {
    await main();

    // 验证构造函数传入的连接参数正确
    expect(EventHubProducerClient).toHaveBeenCalledWith(
      "EVENT HUBS NAMESPACE CONNECTION STRING",
      "EVENT HUB NAME"
    );
    // 验证createBatch方法被调用1次
    expect(EventHubProducerClient.mock.results[0].value.createBatch).toHaveBeenCalledTimes(1);
    // 验证tryAdd被调用3次,传入的事件内容符合预期
    expect(mockTryAdd).toHaveBeenCalledTimes(3);
    expect(mockTryAdd).toHaveBeenNthCalledWith(1, { body: "First event" });
    expect(mockTryAdd).toHaveBeenNthCalledWith(2, { body: "Second event" });
    expect(mockTryAdd).toHaveBeenNthCalledWith(3, { body: "Third event" });
    // 验证sendBatch方法被调用,且传入的是生成的批次对象
    expect(EventHubProducerClient.mock.results[0].value.sendBatch).toHaveBeenCalledWith(mockBatch);
    // 验证close方法被正常调用
    expect(EventHubProducerClient.mock.results[0].value.close).toHaveBeenCalledTimes(1);
  });
});

如果使用其他测试框架如Mocha+Sinon,核心逻辑一致,只需替换对应的stub实现方式即可,无需调整原有业务代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 03:18:02