ExampleSignalR/TestProject/Tests/HubTest.cs

63 lines
1.7 KiB
C#
Raw Permalink Normal View History

2024-11-13 15:38:13 +05:00
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
namespace ExampleSignalR.Test.Tests;
public class HubTest : BaseIntegrationTest
{
private const string url = $"wss://localhost/chatHub";
private readonly WebAppFactoryFixture _factory;
public HubTest(WebAppFactoryFixture factory) : base(factory)
{
_factory = factory;
}
[Fact]
public async Task ConnectToSignalRHub()
{
var hubConnection = await CreateHubConnection();
}
[Fact]
public async Task SignalRHubResponsibility()
{
var hubConnection = await CreateHubConnection();
bool success = false;
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
using var scope = _factory.Services.CreateScope();
var messageService = scope.ServiceProvider.GetRequiredService<IMessageService>();
var testMessage = messageService.GetMessage();
if (message == testMessage)
{
success = true;
}
});
await hubConnection.InvokeAsync("SendMessage", nameof(HubTest), "test");
await Task.Delay(10000);
if (!success)
{
throw new Exception();
}
}
private async Task<HubConnection> CreateHubConnection()
{
var server = _factory.Server;
var hubConnection = new HubConnectionBuilder()
.WithUrl(url, options =>
{
options.HttpMessageHandlerFactory = _ => server.CreateHandler();
})
.Build();
await hubConnection.StartAsync();
return hubConnection;
}
}