是否可以从HubConnection初始化Microsoft.AspNetCore.TestHost.TestServer

下面的示例在HttpRequestException处引发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;
        }
    }
}

最佳答案

您需要调用testServer.CreateHandler()并将HttpMessageHandler传递给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;
}


不过,这不适用于websocket(我在这里https://github.com/aspnet/SignalR/issues/1595为此打开了一个问题

08-27 22:18