Search code examples
asp.net-coresignalrasp.net-core-signalr

Initializing HubConnection from TestServer in ASP.NET Core SignalR


Is is possible to initialize HubConnection from Microsoft.AspNetCore.TestHost.TestServer?

The example below throws HttpRequestException(Not Found) exception at await hubConnection.StartAsync();

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.TestHost;
using Xunit;

namespace FunctionalTests
{
    public class PubSubScenarios
    {
        [Fact]
        public async Task SignalRHubTest_Foo()
        {
            var webHostBuilder = WebHost.CreateDefaultBuilder().UseStartup<Startup>();

            using (var testServer = new TestServer(webHostBuilder))
            {
                var hubConnection = await StartConnectionAsync(testServer.BaseAddress);                
            }
        }

        private static async Task<HubConnection> StartConnectionAsync(Uri baseUri)
        {
            var hubConnection = new HubConnectionBuilder()
                .WithUrl($"http://{baseUri.Host}/fooHub")
                .WithConsoleLogger()
                .Build();

            await hubConnection.StartAsync();

            return hubConnection;
        }
    }
}

Solution

  • You need to call testServer.CreateHandler() and pass the HttpMessageHandler to WithMessageHandler:

    [Fact]
    public async Task SignalRHubTest_Foo()
    {
        var webHostBuilder = WebHost.CreateDefaultBuilder().UseStartup<Startup>();
    
        using (var testServer = new TestServer(webHostBuilder))
        {
            var hubConnection = await StartConnectionAsync(testServer.CreateHandler());                
        }
    }
    
    private static async Task<HubConnection> StartConnectionAsync(HttpMessageHandler handler)
    {
        var hubConnection = new HubConnectionBuilder()
            .WithUrl($"http://test/fooHub", options =>
            {
                options.Transports = HttpTransportType.LongPolling;
                options.HttpMessageHandlerFactory = _ => handler;
            })
            .Build();
    
        await hubConnection.StartAsync();
    
        return hubConnection;
    }
    

    This won't work for websockets though (I opened an issue for this here https://github.com/aspnet/SignalR/issues/1595