I have trying to write integration tests for my SignalR chat application. But the connection.On() callbacks never gets fired. While debugging I have made sure InvokeAsync works perfectly fine but not the callbacks Also I have tested my hub with Angular client and it works fine.
Test.cs
public sealed class ChatHubTest : ControllerTests
{
private IHost? host_;
[Test]
public async Task ReplyWithTheSameMessageWhenInvokeSendMethod()
{
//var message = "Integration Testing in Microsoft AspNetCore SignalR";
string echo = "";
var hostBuilder = new HostBuilder()
.ConfigureWebHost(webHost => _ = webHost
.UseTestServer()
.UseStartup<Startup>()
.UseEnvironment("IntegrationTest"));
host_?.Dispose();
host_ = await hostBuilder.StartAsync();
TestServer server = host_.GetTestServer();
var connection = new HubConnectionBuilder()
.WithUrl(
"http://localhost:5000/hub/chat?username=21671", options =>
{
options.AccessTokenProvider = () => Task.FromResult("hello");
options.HttpMessageHandlerFactory = _ => server.CreateHandler();
})
.Build();
using IDisposable handler = connection.On<(int, string)>(WebSocketActions.GroupAction, msg =>
{
(_, echo) = msg;
_ = echo.Should().Be("Typing");
});
await connection.StartAsync();
await connection.InvokeAsync("JoinGroup", "group1");
await connection.InvokeAsync("SendToGroup", "group1", 123, "Typing");
_ = echo.Should().Be("Typing");
}
}
Hub.cs
public sealed class ChatHub : Hub
{
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Join a socket group </summary>
///
/// <param name="group"> Identifier for the group. </param>
///
/// <returns> . </returns>
//[Authorize(Policy = "CustomHubAuthorizatioPolicy")]
public async Task JoinGroup(string group)
{
await Groups.AddToGroupAsync(Context.ConnectionId, group);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Send action to group </summary>
///
/// <param name="group"> Identifier for the group. </param>
/// <param name="userId"> Identifier for the user. </param>
/// <param name="action"> Action to send </param>
///
/// <returns> . </returns>
//[Authorize(Policy = "CustomHubAuthorizatioPolicy")]
public async Task SendToGroup(string group, int userId, string action)
{
await Clients.Group(group).SendAsync(WebSocketActions.GroupAction, userId, action);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Leave group </summary>
///
/// <param name="group"> Identifier for the group. </param>
///
/// <returns> . </returns>
//[Authorize(Policy = "CustomHubAuthorizatioPolicy")]
public async Task LeaveGroup(string group)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, group);
}
}
The hub works with angular client. Thanks In Advance.