简体   繁体   English

.NET6 隔离 Azure Function 单元和集成测试导致 gRPC 异常

[英].NET6 Isolated Azure Function Unit and Integration Test causes gRPC exception

I have an isolated Azure Function that makes couple of HTTP POST calls.我有一个隔离的 Azure Function,它进行了几个 HTTP POST 调用。 I am trying to write an integration test for them.我正在尝试为他们编写集成测试。 But the test setup fails with a gRPC error.但是测试设置失败并出现 gRPC 错误。

Here is the Program.cs that configures the HttpClient with services.AddHttpClient();这是使用 services.AddHttpClient() 配置 HttpClient 的 Program.cs;

public class Program
{

    public static void Main()
    {
        var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureServices(services =>
            {
                services.AddHttpClient();
            }).Build();

        host.Run();
    }
}

The sample function looks like this:样本 function 如下所示:

public class AzFunctionEndpoint
{        
    public AzFunctionEndpoint(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILoggerFactory loggerFactory)
    {
        logger = loggerFactory.CreateLogger<ResolveEndpoint>();
        this.httpClientFactory = httpClientFactory;
        this.configuration = configuration;
    }

    [Function("azfunction")]
    public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = "azs/azfunction")] HttpRequestData req)
    {
        
        // Couple of other HTTP calls using httpClientFactory
        
        // return
        var res = req.CreateResponse(HttpStatusCode.OK);
        return res;
        
    }        

    private readonly IConfiguration configuration;
    private readonly IHttpClientFactory httpClientFactory;
    private readonly ILogger logger;
}

The Function runs correctly on local machine and when deployed to Azure. Function 在本地机器上正确运行,并在部署到 Azure 时正确运行。

Now I try and create an integration test with现在我尝试创建一个集成测试

public class AzFunctionEndpointIntegrationTests
{
    public AzFunctionEndpointIntegrationTests()
    {
        factory = new WebApplicationFactory<Program>();
        var clientFactory = factory.Services.GetService<IHttpClientFactory>();

        // THIS LINE CAUSES gRPC host error 
        client = clientFactory.CreateClient();
    }

    [Fact]
    public async Task AzFunction_Should_BeOK()
    {
        // POST to the azure function
        HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(HttpMethods.Post), "api/azs/azfunction");

        var response = await client.SendAsync(request);

        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
    }

    private HttpClient client;
    private WebApplicationFactory<Program> factory;
}

The test code that tries to create HttpClient to invoke my function causes this exception尝试创建 HttpClient 以调用我的 function 的测试代码导致此异常

client = clientFactory.CreateClient();

System.InvalidOperationException: The gRPC channel URI 'http://:51828' could not be parsed. System.InvalidOperationException:无法解析 gRPC 通道 URI“http://:51828”。

I don't quite understand what is this error.我不太明白这个错误是什么。 Any help on writing integration tests for Azure Functions is appreciated.感谢任何有关为 Azure 函数编写集成测试的帮助。

System.InvalidOperationException: The gRPC channel URI 'http://:51828' could not be parsed. System.InvalidOperationException:无法解析 gRPC 通道 URI“http://:51828”。

I don't quite understand what is this error.我不太明白这个错误是什么。 Any help on writing integration tests for Azure Functions is appreciated.感谢任何有关为 Azure 函数编写集成测试的帮助。

Below are the few workaround may help to fix the above issue.以下是一些可能有助于解决上述问题的解决方法。

  • Based on this GitHub issue the root cause we have observed that, May be due to the usage of incorrect run/debug configuration the IDE you are using.基于这个GitHub issue ,我们观察到的根本原因可能是由于您使用的 IDE 使用了不正确的run/debug配置。

Please make sure that you are using the same as suggested on the given gitHub link to run the application.请确保您使用的是给定gitHub link中建议的相同方式来运行应用程序。

To write an Integration test you can refer this Example for your function app .要编写集成测试,您可以为您的 function 应用参考此示例

Example of sample code:-示例代码示例:-

test.cs

[TestClass]
public class DefaultHttpTriggerTests
{
    private HttpClient _http;

    [TestInitialize]
    public void Initialize()
    {
        this._http = new HttpClient();
    }

    [TestCleanup]
    public void Cleanup()
    {
        this._http.Dispose();
    }

    [TestMethod]
    public async Task Given_OpenApiUrl_When_Endpoint_Invoked_Then_It_Should_Return_Title()
    {
        // Arrange
        var requestUri = "http://localhost:7071/api/openapi/v3.json";

        // Act
        var response = await this._http.GetStringAsync(requestUri).ConfigureAwait(false);
        var doc = JsonConvert.DeserializeObject<OpenApiDocument>(response);

        // Assert
        doc.Should().NotBeNull();
        doc.Info.Title.Should().Be("OpenAPI Document on Azure Functions");
        doc.Components.Schemas.Should().ContainKey("greeting");

        var schema = doc.Components.Schemas["greeting"];
        schema.Type.Should().Be("object");
        schema.Properties.Should().ContainKey("message");

        var property = schema.Properties["message"];
        property.Type.Should().Be("string");
    }
}

For more information please refer the below links:-有关更多信息,请参阅以下链接:-

SO THREAD:- System.InvaliOperationException: The gRPC channel URI 'http://0' could not be parsed . SO THREAD:- System.InvaliOperationException: The gRPC channel URI 'http://0' could not be parsed

MICROSOFT DOCUMENTATION:- Guide for running C# Azure Functions in an isolated process MICROSOFT 文档:- 运行 C# Azure 隔离进程中函数的指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Azure Function (.NET6) 中读取和写入相同的 Blob 文件 - How to Read & Write to same Blob file in Azure Function (.NET6) 如何在 Visual Studio 2019 和 .NET 中的不同端口上运行 ISOLATED Azure Function 应用程序 5 隔离 - How to run ISOLATED Azure Function app on a different port in Visual Studio 2019 & .NET 5 Isolated 通过 Azure SignalR 连接 .net6 网络服务和 .net6 wpf 应用程序 - Connect .net6 web-service and .net6 wpf application via Azure SignalR 单元测试 Azure 事件中心触发器(Azure 函数) - Unit test Azure Event Hub Trigger (Azure Function) azure function 重试场景的单元测试用例 - nodejs - azure function unit test cases for retry scenario - nodejs Cookies 未发送到客户端(静态 web 应用程序)- Azure 隔离 Function - Cookies are not sent to client (static web app) - Azure Isolated Function 独立 Blazor 具有 Azure Active Directory 身份验证的 WASM.Net6 应用程序在本地工作,而不是部署到 Azure Static 应用程序服务 - Standalone Blazor WASM .Net6 Application with Azure Active Directory Authentication works locally, not when deployed to Azure Static App Service .Net Core 3.1 Function 应用程序单元测试尝试查找 System.Runtime 4.2.2.0 失败 - .Net Core 3.1 Function App Unit Test Fails trying to find System.Runtime 4.2.2.0 如何对预定的 firebase 功能进行单元测试? - How to unit test scheduled firebase function? Azure function 运行时集成不起作用 - Azure function runtime integration doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM