【问题标题】:Unable to connect to the remote server when using localhost to sent http request in unit test在单元测试中使用localhost发送http请求时无法连接到远程服务器
【发布时间】:2021-07-28 09:31:14
【问题描述】:

我有一个基本的单元测试来检查是否设置了 http 请求的标头:

    public async Task HeaderNotFound()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
        // ...set the operation context
        await client.SendAsync(request, CancellationToken.None);
        // ...assert that the needed header are added
    }

客户端在测试类ctor中设置了自定义处理程序:

client = HttpClientFactory.Create(new SomeHandlerThatAddHeader());

上述测试过去运行时没有任何问题,但在我们更新构建管道中使用的构建代理池后开始永久失败。在以下异常中运行测试结果:

无法建立连接,因为目标机器主动 拒绝它 127.0.0.1:80

我可以简单地将 uri 切换到像 google.com 这样的有效 uri(因为似乎 localhost 上没有任何内容),但我想保留 localhost(我也知道在单元测试时建立活动连接会使其更多就像一个 int 测试)。最后模拟 Httpclient 客户端将覆盖添加的DelegatingHandler,对于如此简单的测试来说似乎有点过头了!

请问我该如何解决? 任何帮助表示赞赏。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-core httpclient


    【解决方案1】:

    如果本地主机上没有运行任何内容,则无法建立与本地主机的连接,因此需要 HTTP 服务器。

    您指定仅在使用后才添加标头

    client.SendAsync(request, CancellationToken.None);
    

    因此您必须向有效服务器执行 HTTP 请求。

    替代方案:

    1. 如您所述,请使用有效的服务器地址,例如 google.com(确保防火墙允许)
    2. 将服务器添加到localhost并连接它(IIS / python -m SimpleHTTPServer / etc)

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多