如何在signalr2中添加组支持到模拟客户端?X单元测试框架

本文关键字:客户端 模拟 框架 单元测试 支持 signalr2 添加 | 更新日期: 2023-09-27 18:01:20

我使用Moq为我的signalr2建立一个UnitTest框架。x应用程序。我目前正在模拟我的客户端:

var mockClients = new Mock<IHubCallerConnectionContext>();
Clients = mockClients.Object;

为了测试,我需要测试通过Group发送消息:

Clients.Group(groupName).sendSomeMessage(message);

如何添加组支持到我的模拟客户端?

如何在signalr2中添加组支持到模拟客户端?X单元测试框架

检查一下:https://github.com/SignalR/SignalR/blob/release/tests/Microsoft.AspNet.SignalR.Tests/Server/Hubs/HubFacts.cs

 public void HubsGroupAreMockable()
        {
            var hub = new MyTestableHub();
            var mockClients = new Mock<IHubCallerConnectionContext<dynamic>>();
            var groups = new Mock<IClientContract>();
            hub.Clients = mockClients.Object;
            groups.Setup(m => m.send(It.IsAny<string>())).Verifiable();
            mockClients.Setup(m => m.Group("test")).Returns(groups.Object);
            hub.SendGroup("test", "foo");
            groups.VerifyAll();
        }

您可以参考SingalR团队的本教程

如果你想检查某个组是否收到通知,你应该能够这样做(这是signalr2):

public interface IClientContract
{
    void RaiseAlert(string message);
}
[Test]
public void NotifiesOnlySpecifiedGroupWhenGroupIdSent()
{
    // Adapted from code here: https://github.com/SignalR/SignalR/blob/dev/tests/Microsoft.AspNet.SignalR.Tests/Server/Hubs/HubFacts.cs
    // Arrange
    // Set up the individual mock clients
    var group1 = new Mock<IClientContract>();
    var group2 = new Mock<IClientContract>();
    var group3 = new Mock<IClientContract>();
    group1.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();
    group2.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();
    group3.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();
    // set the Connection Context to return the mock clients
    var mockClients = new Mock<IHubCallerConnectionContext<dynamic>>();
    mockClients.Setup(m => m.Group("1")).Returns(group1.Object);
    mockClients.Setup(m => m.Group("2")).Returns(group2.Object);
    mockClients.Setup(m => m.Group("3")).Returns(group3.Object);
    // Assign our mock context to our hub
    var hub = new NotificationsHub
    {
        Clients = mockClients.Object
    };
    // Act
    hub.RaiseNotificationAlert("2");
    // Assert
    group1.Verify(m => m.RaiseAlert(It.IsAny<string>()), Times.Never);
    group2.Verify(m => m.RaiseAlert(""), Times.Once);
    group3.Verify(m => m.RaiseAlert(It.IsAny<string>()), Times.Never);
}

上面的代码正在检查我的NotificationsHub.RaiseAlert(string groupId)方法是否只在客户端为我传入的特定groupId触发。

这是正在测试的集线器:

public class NotificationsHub : Hub
{
    public void RaiseAlert(string message)
    {
        Clients.All.RaiseAlert(message);
    }
    public void RaiseNotificationAlert(string groupId)
    {
        if (groupId== null)
        {
            // Notify all clients
            Clients.All.RaiseAlert("");
            return;
        }
        // Notify only the client for this userId
        Clients.Group(groupId).RaiseAlert("");
    }
}