azure-functions - Azure Functions 使用静态属性测试函数

标签 azure-functions

我可以使用 Xunit 测试我的 Azure Function,如下所示:

var req = GenerateReq();
var res = await MyFunc.Run(req, logger);

如果在我的函数中我生成一个像这样的 CosmosDb DocumentClient:

    static DocumentClient docClient = GetCustomClient();

    private static DocumentClient GetCustomClient()
    {
        string cosmosUrl = string.Empty;
        string cosmosKey = string.Empty;
        cosmosUrl = Environment.GetEnvironmentVariable("cosmosUrl");
        cosmosKey = Environment.GetEnvironmentVariable("cosmosKey");
        DocumentClient customClient = new DocumentClient(new Uri(cosmosUrl), cosmosKey,
            new ConnectionPolicy
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp,
                // Customize retry options for Throttled requests
                RetryOptions = new RetryOptions()
                {
                    MaxRetryAttemptsOnThrottledRequests = 10,
                    MaxRetryWaitTimeInSeconds = 30
                }
            });
        return customClient;
    }

当我尝试访问 docClient 时,出现异常:

The type initializer for 'MyFunc.Get' threw an exception.

有办法解决这个问题吗?

最佳答案

这可能是由错误的静态构造函数或静态属性/字段的错误内联初始化引起的。例如:

class MyFunc
{
    static MyFunc()
    {
        //buggy code here
    }
    static DocumentClient docClient = Buggy_GetCustomClient(); // <-- or here
}

在首次使用 MyFunc 之前,上述内容将导致 TypeInitializationException

当该代码运行时,您是否定义了环境变量 cosmosUrlcosmosKey如果没有,则可能是原因所在。 GetCustomClient 最终将引发异常,并且该异常将被包装在 TypeInitializationException 中。

正如 Napoloeon 的回答中所建议的,我建议使用依赖项注入(inject)来获取 IDocumentClient 的实例(假设您使用的是函数 v2)。看看这个answer显示如何在 Azure Functions v2 中注入(inject)和使用 IDocumentClient。 Azure函数的DI支持的官方文档是here .

关于azure-functions - Azure Functions 使用静态属性测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57477644/

相关文章:

azure - 通过 ARM 模板设置 Azure 主机/功能键

xml - 如何使用 Azure APIM 创建 OCSP 请求和验证响应?

python - 如何在python的azure函数中使用req.get_body(),其目的是什么?

c# - Azure函数 "Unable to find assembly"

c# - azure 函数中的 HTTP 补丁

Azure 逻辑应用工作流与多个数据库集成

c# - Azure Function 启动的配置未被调用

.net - 了解 Azure Functions 行为

azure - 将 Azure Function App 从专用应用服务计划切换到高级

azure - 如何通过 Bicep 将功能应用程序键添加到logicapp应用程序设置