模拟 Azure 函数的 BlobClient

Mock BlobClient for Azure Function

我有一个带有 blob 触发器的 Azure 函数,在我的函数方法 args 中,我通过 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))

附加参考a:

*代码仅供演示,参考资料给出了如何使用BlobsModelFactory的线索