使用 ClientWebSocket .net 核心测试 TestHost.WebSocketClient

Testing TestHost.WebSocketClient with ClientWebSocket .net core

我已经按照 this and this or this 教程在 .net 核心中构建了一个 WebSocket Web 应用程序。现在我正在尝试使用 Microsoft.AspNetCore.TestHost

对此编写一些 integration 测试

我创建 WebSocket 的方式

public static WebSocketClient StartWebSocketServer(string url)
{
    var baseAddress = $"http://{url}";
    var builder =
        WebHost.CreateDefaultBuilder(new string[]{})
            .UseEnvironment("Development")
            .ConfigureLogging((ctx, logging) => logging.AddConsole())
            .UseUrls(baseAddress)
            .UseStartup<SocketsTestStartup>();

    var server = new TestServer(builder);
    return server.CreateWebSocketClient();
}

而 websocket 客户端的创建是在下面的代码中完成的

ClientWebSocket testAppClient = new ClientWebSocket();
await
    testAppClient 
    .ConnectAsync(
        new Uri("ws://loclahost:52015/local"),
        CancellationToken.None);

local是websocket服务器上的路径名

Startup.cs

app.MapWebSocketManager(
    "/local",
    serviceProvider.GetService<LocalServiceSocketHandler>());

无论如何,连接产生以下错误

System.Net.WebSockets.WebSocketException : Unable to connect to the remote server

我的问题是如何让 ClientWebSocket 连接到 TestHost.WebSocketClient

我使用以下代码代替 TestServer 运行 WebSocket 网络应用程序

public static IWebHost CreateServer(int port)
{
    var configBuilder = new ConfigurationBuilder();
    configBuilder.AddInMemoryCollection();
    var config = configBuilder.Build();
    config["server.urls"] = $"http://localhost:{port}";

    var host = new WebHostBuilder()
        .ConfigureLogging((ctx, logging) => logging.AddDebug())
        .UseConfiguration(config)
        .UseKestrel()
        .UseStartup<SocketsTestStartup>()
        .Build();

    host.Start();

    return host;
}

基本上,我已经从 aspnet/WebSockets 测试中找到了解决方案

使用 TestServer 以下是我的工作,以防万一它可能对其他人有帮助,这里是代码:

var builder = WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseEnvironment("Development");

var server = new TestServer(builder);
var wsClient = server.CreateWebSocketClient();

var wsUri = new UriBuilder(server.BaseAddress) 
{
    Scheme = "ws"
}.Uri;

await wsClient.ConnectAsync(wsUri, CancellationToken.None);

但是由于最初的问题是使用路径 /local,所以只需要指定 Path 属性:

var wsUri = new UriBuilder(server.BaseAddress) 
{
    Scheme = "ws",

    Path = "local"
}.Uri;

这段代码在我们开发的企业级应用程序中对我有用(在此处查看所有代码:https://github.com/saturn72/Programmer

//Create test server    
var server = new TestServer(builder);

//create websocket client, connect it and to server 
var wsc = server.CreateWebSocketClient();
var uri = new Uri(BaseUri, "ws");
var webSocket = wsc.ConnectAsync(uri, CancellationToken.None).Result;
var buffer = WebSocket.CreateClientBuffer(1024, 1024);

//Start receive data
Task.Run(()=> WebSocket.ReceiveAsync(_buffer, CancellationToken.None));

请记住它是 async,您需要在测试中设置一些延迟