.net 5.0 集成测试,未找到运行状况检查端点

.net 5.0 Integration Test, Health check endpoint not found

我正在尝试测试运行状况检查端点。

我已经使用 .net 核心和 WebApplicationFactory 和 TestServer 实施了集成测试,以测试我的 API 端点。

我编写了测试用例 (xUnit) 来测试我的 API 端点,简单的 API 控制器工作得很好,但它没有找到健康检查端点 - 它不是控制器,它是一个可配置的端点

这里是服务配置

services.AddHealthChecks().AddCheck<PingHealthCheck>("ping_health_check");

配置如下

  endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        // Prevent response caching
        AllowCachingResponses = false,
        ResponseWriter = (context, report) => context.Response
            //Return an object instead of a plain text
            .WriteAsync(JsonConvert.SerializeObject(new {status= report.Status.ToString() })),
        ResultStatusCodes =
            {
                [HealthStatus.Healthy] = StatusCodes.Status200OK,
                [HealthStatus.Degraded] = StatusCodes.Status200OK,
                [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
            }
    })

这是测试用例

[Fact]
public async Task Call_Health_Return_Healthy()
{
    //Arrange 
    //Act
    var response = await _factory.TestHttpClient
        .GetAsync("/health");
    //Assert
    response.StatusCode.Should().BeEquivalentTo(HttpStatusCode.OK);
}

我成功解决了我的问题。原因是允许哪些主机访问健康端点的配置。

问题是,我限制了对端口 5001 的访问(在本地主机中),但是 ApplicationFactory 中的 TestServer 没有任何端口。

这里是配置代码

        /// <summary>
        /// Configures the endpoint.
        /// </summary>
        /// <param name="builder">The application builder. <see cref="IApplicationBuilder"/></param>
        /// <param name="configuration">The IConfiguration builder instance</param>
        public static void ConfigureEndpoint(this IApplicationBuilder builder, IConfiguration configuration)
        {
            var healthConfiguration = configuration.GetSection(nameof(HealthConfiguration)).Get<HealthConfiguration>();
            builder.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHealthChecks("/health", new HealthCheckOptions()
                {
                    // Prevent response caching
                    AllowCachingResponses = false,
                    ResponseWriter = (context, report) => context.Response
                        //Return an object instead of a plain text
                        .WriteAsync(JsonConvert.SerializeObject(new {status = report.Status.ToString()})),
                    ResultStatusCodes =
                    {
                        [HealthStatus.Healthy] = StatusCodes.Status200OK,
                        [HealthStatus.Degraded] = StatusCodes.Status200OK,
                        [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
                    }
                }).RequireHost(string.Join(",",healthConfiguration.Hosts.Select(host=>host)));
            });
        }

而配置部分更改为

 "HealthConfiguration": {
    "Hosts": ["localhost"] 
  },