Модульное тестирование страницы сервера Blazor - как имитировать подключение вторичного клиента signalR, используемое на странице сервера Blazor

Я новый пользователь bUnit, и мне удалось запустить несколько тестов для NavMenu, чтобы понять основные концепции. Однако другая страница Blazor делает запрос к вторичному концентратору signalR для передачи состояния рабочего процесса.

Как имитировать соединение signalR? https://github.com/dotnet/aspnetcore/issues/14924

Страница сервера, которая использует дополнительное соединение signalR для передачи состояния рабочего процесса

 protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                var hubUrl = NavigationManager.BaseUri.TrimEnd('/') + "/motionhub";

                try
                {
                    Logger.LogInformation("Index.razor page is performing initial render, connecting to secondary signalR hub");

                    hubConnection = new HubConnectionBuilder()
                        .WithUrl(hubUrl)
                        .ConfigureLogging(logging =>
                        {
                            logging.AddConsole();
                            logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Information);
                        })
                        .AddJsonProtocol(options =>
                        {
                            options.PayloadSerializerOptions = JsonConvertersFactory.CreateDefaultJsonConverters(LoggerMotionDetection, LoggerMotionInfo, LoggerJsonVisitor);
                        })
                        .Build();

                    hubConnection.On<MotionDetection>("ReceiveMotionDetection", ReceiveMessage);
                    hubConnection.Closed += CloseHandler;

                    Logger.LogInformation("Starting HubConnection");
                    await hubConnection.StartAsync();
                    Logger.LogInformation("Index Razor Page initialised, listening on signalR hub => " + hubUrl.ToString());
                }
                catch (Exception e)
                {
                    Logger.LogError(e, "Encountered exception => " + e);
                }
            }
        }

Класс модульного тестирования-заглушки

 public class IndexTest : TestContext, IDisposable
    {
        private MotionDetectionRepository repo;

        public IndexTest()
        {
            var mock = new Mock<IMotionDetectionSerializer<MotionDetection>>();
            repo = new MotionDetectionRepository(mock.Object, new NullLogger<MotionDetectionRepository>());

            Services.AddScoped<ILogger<MotionDetectionRepository>, NullLogger<MotionDetectionRepository>>();
            Services.AddScoped<ILogger<MotionInfoConverter>, NullLogger<MotionInfoConverter>>();
            Services.AddScoped<ILogger<MotionDetectionConverter>, NullLogger<MotionDetectionConverter>>();
            Services.AddScoped<ILogger<JsonVisitor>, NullLogger<JsonVisitor>>();
            Services.AddScoped<ILogger<WebApp.Pages.Index>, NullLogger<WebApp.Pages.Index>>();
            Services.AddScoped<IMotionDetectionRepository>(sp => repo);
            Services.AddScoped<MockNavigationManager>();
            Services.AddSignalR();
        }

        [Fact]
        public void Test()
        {
            var cut = RenderComponent<WebApp.Pages.Index>();

            Console.WriteLine($"{cut.Markup}");
        }
    }

person anon_dcs3spp    schedule 24.11.2020    source источник


Ответы (1)


Я использую этих брокеров.

public interface IHubConnectionsBroker
{
    HubConnection CreateHubConnection(string endpoint, bool autoReconnect);
}

public interface IChatHubBroker
{
    event EventHandler<ChatMessage> OnReceiveMessage;
    event EventHandler<Exception> OnConnectionClosed;
    event EventHandler<Exception> OnReconnecting;
    event EventHandler<string> OnReconnected;

    bool IsConnected { get; }
    string ConnectionId { get; }
    TimeSpan HandshakeTimeout { get; set; }
    TimeSpan KeepAliveInterval { get; set; }
    TimeSpan ServerTimeout { get; set; }
    ChatHubBrokerState ChatHubBrokerState { get; }
    ValueTask StartAsync();
    ValueTask StopAsync();
    ValueTask SendAsync(ChatMessage message);
    ValueTask DisposeAsync();
}

person Brian Parker    schedule 24.11.2020
comment
Ваше здоровье. Да, этого достаточно, чтобы начать, спасибо, я благодарен :) Похоже, официальная позиция Microsoft - использовать интерфейс оболочки github.com/dotnet/aspnetcore/issues/8133 - person anon_dcs3spp; 24.11.2020