SignalR + .NET Core MVC 多大厅功能单元测试问题咨询
Got it, let's walk through how to properly unit test your multi-lobby SignalR functionality. Since your feature is already up and running, we can focus on validating the two key areas you identified—server-side Hub logic and cross-lobby isolation.
1. Unit Testing the SignalR Hub's Server-Side Logic
First, you'll want to validate that your Hub behaves correctly when clients connect, disconnect, and join specific lobbies. The trick here is to abstract dependencies (like the Hub context) so you don't need a real WebSocket connection for tests.
Key Test Scenarios to Cover
- Verify same-lobby users get notified when someone joins
Use theMicrosoft.AspNetCore.SignalR.Testingpackage along with a mocking framework like Moq to simulate the Hub context. Here's a concrete example:using Moq; using Xunit; using Microsoft.AspNetCore.SignalR; public class LobbyHubTests { [Fact] public async Task UserJoinsLobby_SameLobbyUsersReceiveOnlineNotification() { // Mock the Hub context to track client calls var mockHubContext = new Mock<IHubContext<LobbyHub>>(); var mockClients = new Mock<IHubClients>(); var mockGroup = new Mock<IClientProxy>(); // Set up the mock to return our group proxy when targeting "lobbyA" mockClients.Setup(c => c.Group("lobbyA")).Returns(mockGroup.Object); mockHubContext.Setup(h => h.Clients).Returns(mockClients.Object); // Initialize your lobby service (assuming you have one that handles lobby logic) var lobbyService = new LobbyService(mockHubContext.Object); // Simulate two users joining the same lobby var user1 = new UserConnection { UserId = "user_123", LobbyId = "lobbyA" }; var user2 = new UserConnection { UserId = "user_456", LobbyId = "lobbyA" }; await lobbyService.HandleUserConnected(user1); await lobbyService.HandleUserConnected(user2); // Verify that the Hub sent the "UserOnline" message to the lobby group twice mockGroup.Verify(g => g.SendAsync( "UserOnline", It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); } } - Verify cross-lobby users don't get notified
Repeat the above test but have users join different lobbies (e.g., "lobbyA" and "lobbyB"). Then verify that the Hub only sends notifications to the correct group, and never triggers calls for the unrelated lobby. - Verify same-lobby users get notified when someone disconnects
Similar to the join test, simulate a user disconnecting and validate that the "UserOffline" message is sent only to their lobby group.
Pro Tips for Server-Side Testing
- Extract lobby logic to a service class: Don't put all your lobby management code directly in the Hub class. Moving it to a separate
LobbyServicemakes it much easier to test without dealing with Hub context complexities. - Mock state storage: If you're using a service to track which users are in which lobbies, mock that service to control test data (e.g., pre-populate users in specific lobbies for edge cases).
2. Validating Cross-Lobby Isolation (Integration Testing)
While unit tests cover server logic, integration tests will confirm that the end-to-end flow works as expected—ensuring users in different lobbies truly can't see each other's statuses.
Example Integration Test Flow
- Spin up a test server using
WebApplicationFactory(part of ASP.NET Core's testing tools). - Create two client connections: one joining "lobbyA", another joining "lobbyB".
- Simulate the "lobbyA" user connecting, then check if the "lobbyB" client receives any status updates (it shouldn't).
- Repeat with a second user joining "lobbyA" and confirm the first "lobbyA" client gets the online notification.
Final Notes
Make sure your tests cover edge cases too—like a user joining a non-existent lobby, or multiple users connecting/disconnecting rapidly. This will help catch any race conditions in your lobby state management.
内容的提问来源于stack exchange,提问作者Nicholas Ladefoged




