C#, WebApi

Testing SignalR in ASP.NET Core with Integration Tests

1 min read

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:

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.

Dom, my Hubs are protected with a Jwt Token…

No worries, you can pass your Jwt token for SignalR to use using the options of the WithUrl method. Just enrich your options by assigning your token to the AccessTokenProvider property as such:  o.AccessTokenProvider = () => Task.FromResult(token);

Show me the code!

Here is what my test method looks like

As you can see, you need to send a message to your hub by invoking the SendMessage method in your ChatHub and then setup the receiver through the On<..> method

As mentioned as a comment in the snippet, you need to create a HttpClient through the factory for the Server property to be available.

Note:
I’m using WebSockets with SignalR here. In case you cannot (as your machine does not support WebSockets), change the uri from  ws://localhost/hubs/{hubName} to  http://localhost/hubs/{hubName}

Happy testing!

2018-11-13: I added a sample of the code in my github repo here