在unit testing中模拟SignalR Clients.Group的方法

我正在为SignalR应用程序编写模拟测试用例。 我刚开始在unit testingSignalR应用程序的帮助下,但我的要求与那里显示的示例略有不同。 以下是我在谷歌搜索后所做的代码。

SignalRHub

public class HubServer : Hub { [HubMethodName("SendNofication")] public void GetNofication(string message) { try { Clients.Group("Manager").BroadCast(message); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } 

unit testing

 public interface IClientContract { } [TestMethod] public void GetNoficationTest() { var hub = new HubServer(); var mockClients = new Mock<IHubCallerConnectionContext>(); hub.Clients = mockClients.Object; var all = new Mock(); string message = "Message to send"; mockClients.Setup(m => m.Group("Manager")).Returns(message); mockClients.Setup(m => m.All).Returns(all.Object); hub.GetNofication("Mock call to SingalR hub"); all.VerifyAll(); } 

我是unit testing应用程序的初学者,只是想确认这是否是模拟SignalR组的正确方法。

使用Microsoft.AspNet.SignalR.Tests中的示例

Hubs Group是Mockable

需要使用必要的方法更新客户合同。 在这种情况下,您必须添加Broadcast方法以匹配在Hub中调用它的方式

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

接下来通过设置集线器的依赖关系来安排测试并运行测试中的方法。

 [TestMethod] public void _GetNoficationTest() { // Arrange. var hub = new HubServer(); var mockClients = new Mock>(); var groups = new Mock(); 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(); } 

另一个选择是使用ExpandoObject伪造组, Clients.Group此实例中的Clients.Group返回dynamic

 [TestMethod] public void _GetNoficationTest_Expando() { // Act. var hub = new HubServer(); var mockClients = new Mock>(); 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(m => { actual = m; messageSent = true; }); mockClients.Setup(_ => _.Group(groupName)).Returns((ExpandoObject)groups); // Act. hub.GetNofication(expected); // Assert. Assert.IsTrue(messageSent); Assert.AreEqual(expected, actual); }