Testing TestHost.WebSocketClient with ClientWebSocket .net core

Viewed 5236

I have build a WebSocket web application in .net core by following this and this or this tutorials. Now I am trying to write some integration tests on this by using Microsoft.AspNetCore.TestHost

The way I create the 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();
}

And websocket client creation is done in the code below

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

local is the path name on the websocket server

Startup.cs

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

Anyway, the connection produce the following error

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

My question is how can I ask ClientWebSocket to connect to TestHost.WebSocketClient?

3 Answers

Instead of TestServer, I used the following code to run the WebSocket web app

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;
}

Basically, I have found the solution from aspnet/WebSockets tests

This code worked for me in the enterprise grade app we developed (see all code here: 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));

Bare in mind it is async and you need do set some delay in your test

Related