
In today’s world, real-time applications are increasingly important to provide users with the most up-to-date and interactive experiences. SignalR is a powerful library that simplifies the process of adding real-time functionality to your applications. In this tutorial, we will walk you through the process of building a real-time chat application using SignalR and .NET 7.
services.AddSignalR();
app.UseEndpoints(endpoints =>{endpoints.MapHub<ChatHub>("/chatHub");});
public async Task SendMessage(string user, string message){await Clients.All.SendAsync("ReceiveMessage", user, message);}
"use strict";var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();connection.on("ReceiveMessage", function (user, message) {var msg = user + ": " + message;var li = document.createElement("li");li.textContent = msg;document.getElementById("messagesList").appendChild(li);});connection.start().catch(function (err) {return console.error(err.toString());});document.getElementById("sendButton").addEventListener("click", function (event) {var user = document.getElementById("userInput").value;var message = document.getElementById("messageInput").value;connection.invoke("SendMessage", user, message).catch(function (err) {return console.error(err.toString());});event.preventDefault();});
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>SignalR Chat App</title></head><body><h1>SignalR Chat App</h1><ul id="messagesList"></ul><form><input type="text" id="userInput" placeholder="User" /><input type="text" id="messageInput" placeholder="Message" /><button type="submit" id="sendButton">Send</button></form><script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.10/signalr.min.js"></script><script src="js/chat.js"></script></body></html>
To ensure that our chat application works as expected, let’s create unit tests for the ChatHub class.
In the Solution Explorer, right-click the solution and select “Add” -> “New Project.”
Choose “xUnit Test Project (.NET Core)” and click “Next.”
Name the project “SignalRChatApp.Tests” and click “Create.”
Install necessary NuGet packages:
a. Right-click on the “SignalRChatApp.Tests” project and select “Manage NuGet Packages.” b. Search for “Microsoft.AspNetCore.SignalR” and install the latest version. c. Search for “Microsoft.AspNetCore.TestHost” and install the latest version. d. Search for “Moq” and install the latest version.
Create a new class called “ChatHubTests” in the “SignalRChatApp.Tests” project.
Add the following using statements at the top of the “ChatHubTests” class:
using System.Threading.Tasks;using Microsoft.AspNetCore.SignalR;using Moq;using SignalRChatApp.Hubs;using Xunit;
public class ChatHubTests{[Fact]public async Task SendMessage_BroadcastsMessageToAllClients(){// Arrangevar mockClients = new Mock<IHubCallerClients>();var mockClientProxy = new Mock<IClientProxy>();mockClients.Setup(clients => clients.All).Returns(mockClientProxy.Object);var chatHub = new ChatHub { Clients = mockClients.Object };var user = "TestUser";var message = "TestMessage";// Actawait chatHub.SendMessage(user, message);// AssertmockClients.Verify(clients => clients.All, Times.Once);mockClientProxy.Verify(clientProxy => clientProxy.SendCoreAsync("ReceiveMessage",It.Is<object[]>(args => args[0].Equals(user) && args[1].Equals(message)),default),Times.Once);}}
Run the tests:
a. Open the Test Explorer by clicking on “Test” -> “Test Explorer” in the menu bar. b. Click on “Run All Tests” in the Test Explorer.
You should now see your test pass, ensuring that the “SendMessage” method in the ChatHub class correctly broadcasts the message to all connected clients.
To dive deeper into the topics covered in this post, consider checking out the following resources:
In this tutorial, we built a real-time chat application using SignalR and .NET 7 and added unit tests to verify the functionality. This foundation allows you to explore other real-time application possibilities while maintaining high-quality code through testing. SignalR is an excellent tool for enhancing your applications and providing users with a seamless and interactive experience.
We’d love to hear your feedback on this tutorial! If you have any questions or suggestions for improvement, please don’t hesitate to reach out. You can leave a comment below, or you can contact us through the following channels:
We’ll do our best to address any questions or concerns you may have. We look forward to hearing from you and helping you make the most of building real-time applications with SignalR in .NET 7!
Quick Links
Legal Stuff



