【问题标题】:WebApplicationFactory doesn't (seem to) send out any dataWebApplicationFactory 不(似乎)发送任何数据
【发布时间】:2021-12-22 19:38:47
【问题描述】:

我正在尝试使用 WebApplicationFactory 类型为我的 ASP.NET Core 中间件创建集成测试。

我的目标是模拟 ASP.NET Core 主机,集成应用洞察,并将数据实际发送到真实的 Application Insights 实例,以确保一切按预期工作。

很遗憾,我的测试服务器没有向应用洞察发送任何数据。

这就是我的测试设置的样子。我从WebApplicationFactory 继承如下:

public class WebTestFixture : WebApplicationFactory<Startup>
{
    protected override IHostBuilder CreateHostBuilder()
    {
        var builder = Host.CreateDefaultBuilder();

        builder.ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.UseEnvironment("Testing");
        });

        builder.ConfigureAppConfiguration((context, config) =>
        {
            config.AddUserSecrets<WebTestFixture>();
        });

        return builder;
    }
}

那么我的测试程序集的测试Startup类如下所示:

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();
        services.AddAppInsightsHttpBodyLogging();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
        app.UseAppInsightsHttpBodyLogging();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapPost("/", async ctx =>
            {
                ctx.Response.StatusCode = StatusCodes.Status400BadRequest;
                await ctx.Response.WriteAsync("Hello from integration test");
            });
        });
    }
}

检测密钥存储在 secrets.json 中。

{
  "ApplicationInsights": {
    "InstrumentationKey": "***HIDDEN***"
  }
}

最后是我的测试

public class BodyLoggerMiddlewareIntegrationTests : IClassFixture<WebTestFixture>
{
    private readonly WebTestFixture _factory;

    public BodyLoggerMiddlewareIntegrationTests(WebTestFixture factory) => _factory = factory;

    [Fact]
    public async void BodyLoggerMiddleware_Should_Send_And_Mask_Data()
    {
        // Arrange
        var client = _factory.CreateClient();

        // Act
        var requestBody = new
        {
            Name = "Bommelmaier",
            Password = "Abracadabra!",
            AccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI"
        }; 
        var response = await client.PostAsync("/", new JsonContent(requestBody));

        // Assert
        response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
    }
}

测试通过,我可以在调试日志中看到以下行(为提高可读性而进行了格式化),它告诉我应用洞察发送了我的数据。

Application Insights Telemetry: 
{
  "name": "AppRequests",
  "time": "2021-12-22T19:13:32.8336126Z",
  "iKey": "***HIDDEN***",
  "tags": {
    "ai.application.ver": "15.0.0.0",
    "ai.cloud.roleInstance": "MY_HOST",
    "ai.operation.id": "3fe600bbe13fcf41b1e52a0df7f7465e",
    "ai.operation.name": "POST /",
    "ai.internal.sdkVersion": "aspnet5c:2.18.0+a9fc6af7538cc287d263d9bc216c7910bfc34566",
    "ai.internal.nodeName": "MY_HOST"
  },
  "data": {
    "baseType": "RequestData",
    "baseData": {
      "ver": 2,
      "id": "3857ad615d298e4b",
      "name": "POST /",
      "duration": "00:00:00.2006790",
      "success": false,
      "responseCode": "400",
      "url": "http://localhost/",
      "properties": {
        "_MS.ProcessedByMetricExtractors": "(Name:'Requests', Ver:'1.1')",
        "RequestBody": "{\"Name\":\"Bommelmaier\",\"Password\":\"Abracadabra!\",\"AccessToken\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI\"}",
        "AspNetCoreEnvironment": "Production",
        "ResponseBody": "Hello from integration test",
        "DeveloperMode": "true"
      }
    }
  }
}

但是,即使在等待超过 30 分钟之后,我的 App Insights 实例也没有收到任何东西。任何的想法?我在这里错过了什么?

【问题讨论】:

标签: asp.net-core integration-testing azure-application-insights xunit


【解决方案1】:

谢谢Andreas Wendl。发布您的建议作为帮助其他社区成员的答案。

你可以打开Fiddler,看看这里提到的主机是否有传出流量IP addresses used by Azure Monitor

还要确保在您的传出网络/防火墙/代理/等中允许这些主机/IP。规则。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多