c# - Kestrel 在 xUnit 测试中没有监听

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

我使用这个自定义服务器进行单元测试,我使用 MyStarup 对其进行初始化,加载测试所需的单个中间件。

这之前曾在 net47 上运行过,但在我将项目切换到 .net-core 后就停止了。现在它给了我这个非常有用的异常(exception):

System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 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后就停止了?

最佳答案

我明白了。您需要使用自定义配置来指定 urls值为 Kestrel ,否则它使用一些随机(?)或默认端口 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();
    }

关于c# - Kestrel 在 xUnit 测试中没有监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224717/

相关文章:

android - 为什么在查询Purchases.subscriptions资源时developerPayload字段为空?

c# - Rhino Mocks - 使用 ref/out 参数模拟集合

http-headers - 在 .Net Core 中将 WebHeaderCollection 转换为 NameValueCollection

c# - Android 上的 Xamarin.Forms "App has stopped working"

amazon-web-services - 如何在有约束的情况下在本地测试 AWS 资源

unit-testing - 你如何对 Python DataFrames 进行单元测试

wpf - 如何使用MVVM进行测试优先的开发

c# - Azure Pipeline : dotnet publish fails - assets. json 没有 '.NETCoreApp,Version=v3.1/win-x64' 的目标

c# - 错误 : DEP0500 : The folder "...\Debug\AppX" could not be deleted. 访问路径 'resources.pri' 被拒绝

c# - 上传大文件