首页 > 解决方案 > 在 Azure 队列触发功能单元测试中模拟 ExecutionContext

问题描述

测试队列触发功能时如何模拟 ExecutionContext?下面是我使用 ExecutionContext 获取一些设置值的示例函数,这些设置值在函数的下方使用,我还需要为这些设置提供测试值。

[FunctionName("ProcessQueueFunction")]
public static void Run([QueueTrigger("process-queue", Connection = "AzureWebJobsStorage")]string queueItem, ILogger log, ExecutionContext context)
{
   var config = new ConfigurationBuilder()
       .SetBasePath(context.FunctionAppDirectory)
       .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
       .AddEnvironmentVariables()
       .Build();

       var customConfiguraion = config.GetSection("CustomSection");

       //do stuff...
}

我可以做一些链接这个但是这给了我关于 FunctionAppDirectory 无效或空的错误。我需要将 FunctionAppDirectory 设置为什么?或者这是一种不正确的方法吗?

var mockContext = new Mock<ExecutionContext>();
mockContext.Object.FunctionAppDirectory = string.Empty; //or any other value

ProcessQueueFunction.Run("TestQueueItem", log: logger, context: mockContext.Object);

标签: azureunit-testingazure-functions

解决方案


您可以直接传递执行上下文,无需为了使用属性而模拟一个类。

ExecutionContext executionContext = new ExecutionContext();
executionContext.FunctionAppDirectory = "PATH";

ProcessQueueFunction.Run("TestQueueItem", log: logger, context: executionContext);

推荐阅读