gpt4 book ai didi

c# - Azure 函数的模拟 BlobClient

转载 作者:行者123 更新时间:2023-12-02 22:54:07 27 4
gpt4 key购买 nike

我有一个具有 Blob 触发器的 Azure 函数,在我的函数方法参数中,我通过 BlobClient 公开 Blob 本身以及上传​​的文件的名称。

[FunctionName("MyFunc")]
public async Task RunAsync([BlobTrigger("upload/{name}", Connection = "DataLake")]
BlobClient blob, string name)
{
var propertiesResponse = await blob.GetPropertiesAsync();
var properties = propertiesResponse.Value;
var metadata = properties.Metadata;

//do stuff with metadata

if (metadata.TryGetValue("activityId", out var activityId))
{

}

using (var stream = await blob.OpenReadAsync())
using (var sr = new StreamReader(stream))
{
//do some stuff with blob
}
}

我想对该函数进行单元测试,并尝试模拟 BlobClient,但在使用 Moq 库时遇到问题。我找到了BlobsModelFactory旨在帮助模拟,但我看不到 BlobClient 的任何内容。有人设法模拟 BlobClient 吗?

最佳答案

符合新的Azure SDK guidelines公共(public)方法被标记为virtual,因此可以模拟它们:

A service client is the main entry point for developers in an Azure SDK library. Because a client type implements most of the “live” logic that communicates with an Azure service, it’s important to be able to create an instance of a client that behaves as expected without making any network calls.

  1. Each of the Azure SDK clients follows mocking guidelines that allow their behavior to be overridden:
  2. Each client offers at least one protected constructor to allow inheritance for testing.All public client members are virtual to allow overriding.

如果是 BlobClient 模拟,可以像这样完成*:

var mock = new Mock<BlobClient>();
var responseMock = new Mock<Response>();
mock
.Setup(m => m.GetPropertiesAsync(null, CancellationToken.None).Result)
.Returns(Response.FromValue<BlobProperties>(new BlobProperties(), responseMock.Object))

很多东西,比如 BlobProperties,都可以使用静态类 BlobsModelFactory 来模拟。 ,一些例子:

var blobProps = BlobsModelFactory.BlobProperties(blobType: BlobType.Block);
var result = BlobsModelFactory.BlobDownloadResult(content: null);

其他引用资料:

*代码仅用于演示,引用资料提供了如何使用 BlobsModelFactory 的线索

关于c# - Azure 函数的模拟 BlobClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70632556/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com