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

使用Moq模拟BlobClient.DownloadContentAsync()无返回,是否模拟正确?

BlobClient.DownloadContentAsync() 模拟代码问题排查与修正

你的模拟代码存在几处可能导致未返回预期结果的问题,以下是具体分析和修正方案:

参数匹配不精确

你使用 default 作为 DownloadContentAsync 的参数,但该方法的重载需要匹配 CancellationToken 参数。如果测试代码中调用时传入了非默认的取消令牌,模拟逻辑就不会被触发。

修正方式:使用 It.IsAny<CancellationToken>() 匹配任意取消令牌:

mockBlobClientTrue.Setup(client => client.DownloadContentAsync(It.IsAny<CancellationToken>()))
                  .ReturnsAsync(response);

Response 对象构建可能存在无效依赖

blobContainerClientResponseMock 如果未正确配置,可能导致响应对象异常。如果不需要自定义响应头或状态码,可以简化响应对象的创建:

var response = Response.FromValue(downloadResult, new Mock<ResponseHeaders>().Object);

完整修正后的模拟代码

var blobContent = BinaryData.FromString("this is test data");
var downloadResult = BlobsModelFactory.BlobDownloadResult(content: blobContent);
var response = Response.FromValue(downloadResult, new Mock<ResponseHeaders>().Object);

mockBlobClientTrue.Setup(client => client.DownloadContentAsync(It.IsAny<CancellationToken>()))
                  .ReturnsAsync(response);

验证逻辑示例

调用后检查返回结果的内容是否符合预期:

var result = await mockBlobClientTrue.Object.DownloadContentAsync();
var actualContent = result.Value.Content.ToString();
// 断言 actualContent == "this is test data"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:16:03