在Azure队列触发器功能单元测试中模拟ExecutionContext

时间:2020-04-10 17:30:45

标签: azure unit-testing azure-functions

在测试队列触发功能时如何模拟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);

1 个答案:

答案 0 :(得分:0)

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

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

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