【问题标题】:Kestrel not listening in xUnit testKestrel 没有在 xUnit 测试中监听
【发布时间】:2019-07-27 04:36:52
【问题描述】:

我正在使用此自定义服务器进行单元测试,并使用 MyStarup 对其进行初始化,该服务器加载了我需要进行测试的单个中间件。

这在 net47 之前已经有效,但在我将项目切换到 .net-core 后它停止了。它现在给了我这个非常有用的例外:

System.Net.Sockets.SocketException 无法建立连接,因为目标机器主动拒绝它 127.0.0.1:30001

我使用工厂方法从IClassFixture 创建它并使用HttpClient 调用它,我也使用工厂方法创建它并从同一个夹具中获取它。

public class MyServer : IDisposable
{
    private readonly IWebHost _host;        

    public MyServer(string url) // <-- http://localhost:30001
    {
        _host =
            new WebHostBuilder()
                .UseKestrel()
                .UseUrls(url)                    
                .UseStartup<MyStartup>()
                .Build();

        Task = _host.StartAsync(); // <-- tried RunAsync too, no difference
    }

    public Task Task { get; set; }

    public void Dispose()
    {
        _host.Dispose();
    }
}

所以我的问题是,我怎样才能让它再次工作?

我读过这个Why Kestrel doesn't listen at specified port? ,但它无助于解决它。我无法将它作为控制台运行,它以前可以工作。为什么切换到.net-core后就停止了?

【问题讨论】:

  • 为什么不使用测试服务器进行集成测试
  • @Nkosi 我喜欢掌控一切。如果他们成功了,那么一定有办法:-]
  • 在 .NET Core 中有一个 WebApplicationFactory 类可用于创建应用程序宿主。它可能是您问题的替代解决方案。这也是为集成测试创建主机的推荐方法。 docs.microsoft.com/en-us/dotnet/api/…

标签: c# unit-testing .net-core xunit.net kestrel-http-server


【解决方案1】:

我想通了。您需要使用自定义配置为Kestrel 指定urls 值,否则它使用一些随机 (?) 或默认端口5001。我不想使用hosting.json,所以我使用了InMemoryCollection

    public MyServer(string url)
    {
        var configuration =
            new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    ["urls"] = url
                })
                .Build();

        _host =
            new WebHostBuilder()
                .UseKestrel()
                //.UseUrls(url) // <-- cannot use this, seems to be deprecated
                //.Configure(app => { app.UsePathBase(url); }) // <-- does not work
                .UseConfiguration(configuration)
                .UseStartup<MyStartup>()
                .Build();

        Task = _host.StartAsync();
    }

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多