Ian*_*emp 5 c# azure azure-functions
当前版本的Microsoft.Azure.Functions.Extensions包公开了一个附加属性,使您可以轻松访问为IConfiguration函数提供的内容。以前这需要手动构建服务提供者,这显然是有问题的。
使用该包我FunctionsStartup.cs看起来像这样:
public override void Configure(IFunctionsHostBuilder builder)
{
base.Configure(builder);
var config = builder.GetContext().Configuration; // new in v1.1.0 of Microsoft.Azure.Functions.Extensions
var mySetting = config["MySetting"];
int.Parse(mySetting, out var mySetting);
// ... use mySetting...
}
Run Code Online (Sandbox Code Playgroud)
为了测试我的 HTTP 触发函数,我使用本文作为基础,其中详细介绍了如何手动构建和启动主机来执行我的函数,就好像它在 Azure 中运行一样,类似于TestServerASP.NET Core 中的工作方式:
var host = new HostBuilder()
.ConfigureWebJobs(new FunctionsStartup().Configure)
.Build();
var functionsInstance = ActivatorUtilities.CreateInstance<MyFunctions>(host.Services);
Run Code Online (Sandbox Code Playgroud)
然后我可以执行定义的函数方法MyFunctions来测试它们的响应:
var request = new DefaultHttpRequest(new DefaultHttpContext());
var response = (OkObjectResult)functionsInstance.HttpTriggerMethod(request);
... assert that response is valid
Run Code Online (Sandbox Code Playgroud)
问题是,当我运行测试时,builder.GetContext().Configuration正在返回null,FunctionsStartup.Configure这当然会导致这些测试失败。我该如何解决这个问题?
Ian*_*emp 10
我链接到的文章尚未更新以考虑 的存在builder.GetContext().Configuration,但您可以通过一些调整使其用于测试目的。而不是使用:
var host = new HostBuilder()
.ConfigureWebJobs(new FunctionsStartup().Configure)
.Build();
Run Code Online (Sandbox Code Playgroud)
您需要显式地将主机的设置复制到新的设置中,WebJobsBuilderContext然后将其传递给函数的启动:
var host = new HostBuilder()
.ConfigureWebJobs((context, builder) => new FunctionsStartup().Configure(new WebJobsBuilderContext
{
ApplicationRootPath = context.HostingEnvironment.ContentRootPath,
Configuration = context.Configuration,
EnvironmentName = context.HostingEnvironment.EnvironmentName,
}, builder))
.Build();
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是实现这一目标的完全正确的方法,但它对我来说效果很好。
| 归档时间: |
|
| 查看次数: |
1069 次 |
| 最近记录: |