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

在.NET Graph v5中如何用Moq正确Mock Batch.PostAsync调用?

要搞定client.Batch.PostAsync的Mock,得分两步来:先模拟返回的BatchResponseContent,再让PostAsync返回这个模拟对象。

1. 模拟BatchResponseContent的流返回

业务代码最后会通过GetResponseStreamByIdAsync拿邮件流,所以先给这个方法做Mock:

// 准备测试用的邮件内容,换成你需要的测试数据
var testMailContent = "这是模拟的邮件内容";
var testStream = new MemoryStream(Encoding.UTF8.GetBytes(testMailContent));

// 构造Mock的BatchResponseContent
var mockBatchResponse = new Mock<BatchResponseContent>(MockBehavior.Strict);
mockBatchResponse.Setup(r => r.GetResponseStreamByIdAsync(
    It.IsAny<string>(), // 匹配任意request.Key,也可以换成具体值精准匹配
    It.IsAny<CancellationToken>()))
    .ReturnsAsync(testStream);

2. 模拟Batch.PostAsync方法

接下来让client.Batch.PostAsync返回上面Mock好的BatchResponseContent。注意client.Batch是IBatchRequestBuilder类型,直接Mock它的PostAsync即可:

// 假设你的mockClient是Mock<GraphServiceClient>实例
mockClient.Setup(c => c.Batch.PostAsync(
    It.IsAny<BatchRequestContentCollection>(),
    It.IsAny<CancellationToken>()))
    .ReturnsAsync(mockBatchResponse.Object);

完整Mock代码整合

把你已有的Mock代码和新增的部分合起来:

// 你之前已经写好的ConvertToNativeRequestAsync Mock
mockRequestAdapter.Setup(adapter => adapter.ConvertToNativeRequestAsync<HttpRequestMessage>(
    It.IsAny<RequestInformation>(),
    It.IsAny<CancellationToken>()))
    .ReturnsAsync((RequestInformation requestInformation, CancellationToken token) =>
    {
        var message = new HttpRequestMessage();
        var mailId = (string)requestInformation.PathParameters["message%2Did"];
        message.Content = new StringContent(mailId);
        return message;
    });

// 新增的BatchResponseContent Mock
var testMailContent = "测试邮件内容";
var testStream = new MemoryStream(Encoding.UTF8.GetBytes(testMailContent));
var mockBatchResponse = new Mock<BatchResponseContent>(MockBehavior.Strict);
mockBatchResponse.Setup(r => r.GetResponseStreamByIdAsync(
    It.IsAny<string>(),
    It.IsAny<CancellationToken>()))
    .ReturnsAsync(testStream);

// Mock Batch.PostAsync
mockClient.Setup(c => c.Batch.PostAsync(
    It.IsAny<BatchRequestContentCollection>(),
    It.IsAny<CancellationToken>()))
    .ReturnsAsync(mockBatchResponse.Object);

额外提示

如果需要精准匹配特定的请求Key或者Batch内容,可以把It.IsAny<>换成具体的匹配条件,比如:

  • 匹配特定Key:It.Is<string>(key => key == expectedRequestKey)
  • 匹配特定Batch集合:可以检查集合里的请求步骤是否符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:53:09