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
?
Using the TestServer the following works on my end and just in case it may help someone else, here's the code:
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);
But since the original question is using the path /local
one would just need to specify the Path
property:
var wsUri = new UriBuilder(server.BaseAddress)
{
Scheme = "ws",
Path = "local"
}.Uri;