Testing SignalR in ASP.NET Core with Integration Tests
As promised in my last post, I’m following up on how to test your SignalR hubs in an end to end manner using TestServer. This post is a build up on my last post so if you haven’t read it, go do so now! Setup I have a Hub named ChatHub that has the following method:
1 2 3 4 |
public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("OnMessageReceived", user,message); } |
My clients all are connected to (listen to) a method to receive messages called OnMessageReceived. Tests In my test class, I created a method to help me start my connection. If you plan on testing multiple hubs, you may want to move this method to a helper class.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static async Task<HubConnection> StartConnectionAsync(HttpMessageHandler handler, string hubName) { var hubConnection = new HubConnectionBuilder() .WithUrl($"ws://localhost/hubs/{hubName}", o => { o.HttpMessageHandlerFactory = _ => handler; }) .Build(); await hubConnection.StartAsync(); return hubConnection; } |
Dom, my Hubs are protected with a Jwt Token… No worries, you can pass your…
Read more