gpt4 book ai didi

unit-testing - 使用 HttpRequestMessage 对 Azure Functions 进行单元测试

转载 作者:行者123 更新时间:2023-12-04 05:30:12 30 4
gpt4 key购买 nike

我在尝试在 Visual Studio 中对 HTTP 触发器 Azure Functions 进行单元测试时遇到了一些问题。我创建了一个 GitHub 存储库 ( https://github.com/ericdboyd/TestingAzureFunctions ),其中包含一个示例解决方案,其中包含一个 Azure Function 项目和一个演示问题的单元测试项目。

首先,当我引入 Microsoft.AspNet.WebApi.Core 时,在尝试使用 IContentNegotiator 时,它会在 System.Web.Http 和 Microsoft.AspNetCore.Mvc.WebApiCompatShim 之间产生冲突。解决这个问题的唯一方法是使用以下命令在测试项目的 csproj 文件中为 WebApiCompatShim 指定别名:

<Target Name="ChangeAliasesOfStrongNameAssemblies" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Microsoft.AspNetCore.Mvc.WebApiCompatShim'">
<Aliases>webapicompatshim</Aliases>
</ReferencePath>
</ItemGroup>

一旦我克服了这个错误,我就遇到了这个我无法解决的问题。使用 HttpRequestMessage.CreateResponse 扩展方法在 Azure Function 中返回响应时,我收到“未注册类型‘System.Net.Http.Formatting.IContentNegotiator’的服务”。当我尝试测试它时。我尝试构建一个 HttpRequestMessage,我认为应该使用以下代码(也可以在 GitHub 存储库中找到)与该扩展方法一起使用,但它失败了,我已经尝试了几个小时来解决这个问题。

IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.AddSingleton(typeof(IContentNegotiator), typeof(DefaultContentNegotiator));
IServiceProvider serviceProvider = services.BuildServiceProvider();

var httpContext = new DefaultHttpContext {RequestServices = serviceProvider};

var httpConfiguration = new HttpConfiguration();

HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(content, Encoding.UTF8, "application/json"),
Properties =
{
{ HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },
{ nameof(HttpContext), httpContext}
}
};

如果我不使用 CreateResponse 扩展方法,而只创建 HttpResponseMessage 对象,则效果很好。

只是为了设置一些额外的上下文,我知道这不是对 Azure Function 执行的代码进行单元测试的最佳方法。我正在更精细地对该代码进行单元测试。但我希望能够对正在执行 http 请求和对该逻辑的响应之间的映射的 Azure 函数进行单元测试。

GitHub 存储库中有两个 Azure Functions 和两个单元测试,一组带有扩展方法,一组没有演示问题。但其他一切都是一样的。

最佳答案

不是您问题的直接答案,但它应该可以帮助您继续前进。

您正在使用 Azure Functions v2 - .NET 标准版本。该版本目前处于测试阶段,因此它有点阴暗:缺少文档并且存在一些问题。

在 V2 中,建议您使用 HttpRequest 类和 IActionResult 而不是“经典”HttpRequestMessageHttpResponseMessage 。默认模板的签名如下:

public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req, TraceWriter log)

这应该使您能够摆脱垫片并以类似于 ASP.NET Core 的方式对功能进行单元测试。

关于unit-testing - 使用 HttpRequestMessage 对 Azure Functions 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49498176/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com