Ways to mock SignalR Clients.Group in unit test

杀马特。学长 韩版系。学妹 提交于 2019-12-04 16:29:51

Using examples from Microsoft.AspNet.SignalR.Tests

Hubs Group Are Mockable

The client contract needs to be updated with the necessary methods. In this case you will have to add Broadcast method to match how it is called in the Hub

public interface IClientContract {
    void Broadcast(string message);
}

Next arrange the test by setting up the dependencies for the hub and exercise the method under test.

[TestMethod]
public void _GetNoficationTest() {
    // Arrange.
    var hub = new HubServer();
    var mockClients = new Mock<IHubCallerConnectionContext<dynamic>>();
    var groups = new Mock<IClientContract>();
    var message = "Message to send";
    var groupName = "Manager";

    hub.Clients = mockClients.Object;
    groups.Setup(_ => _.Broadcast(message)).Verifiable();
    mockClients.Setup(_ => _.Group(groupName)).Returns(groups.Object);

    // Act.
    hub.GetNofication(message);

    // Assert.
    groups.VerifyAll();
}

Another option would be to fake the group using an ExpandoObject given that Clients.Group in this instance returns dynamic

[TestMethod]
public void _GetNoficationTest_Expando() {
    // Act.
    var hub = new HubServer();
    var mockClients = new Mock<IHubCallerConnectionContext<dynamic>>();
    dynamic groups = new ExpandoObject();
    var expected = "Message to send";
    string actual = null;
    var groupName = "Manager";
    bool messageSent = false;

    hub.Clients = mockClients.Object;
    groups.Broadcast = new Action<string>(m => {
        actual = m;
        messageSent = true;
    });
    mockClients.Setup(_ => _.Group(groupName)).Returns((ExpandoObject)groups);

    // Act.
    hub.GetNofication(expected);

    // Assert.
    Assert.IsTrue(messageSent);
    Assert.AreEqual(expected, actual);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!