How do I make fun of the SignalR HubContext in the controller for unit testing?

I am using SignalR in an MVC5 project. I make calls inside the controller as follows:

private Microsoft.AspNet.SignalR.IHubContext blogHubContext = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<BlogHub>(); blogHubContext.Clients.All.addNewBlogToPage(RenderPartialViewToString("Blog", model)); 

I am trying to perform unit test actions inside this controller. Unit tests worked fine until I added SignalR functionality. Now I'm trying to figure out how to mock a HubContext. I have 2 options.

  • I am setting up a hub in the constructor, so I have something like the following:

     private Microsoft.AspNet.SignalR.IHubContext blogHubContext; public BlogController(Microsoft.AspNet.SignalR.IHubContext topicHub = null){ blogHubContext = (blogHub != null) ? blogHub : Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<BlogHub>(); } 

    Then I can somehow make fun of the HubContext and pass it to the controller when I create it in the unit test. So far I only have this:

     Mock<IHubContext> blogHub = new Mock<IHubContext>(); 

    (Note: I simplified everything to focus only on the SignalR side. There are also repositories used in the controller, etc.)

  • As an alternative, I thought about creating another class for porting the hub, and then just called from this function to make calls to the hub. I find it much easier to mock my unit tests, but I'm not sure if this is a good idea.

Direction is appreciated. Or are both acceptable ways forward? Thanks.

+6
source share
1 answer

Update, see this code, I base this on the default MVC pattern. There is no need for a wrapper class.

 public class HomeController : Controller { private readonly IHomeHub _hub; public HomeController(IHomeHub hub) { _hub = hub; } public ActionResult Index() { _hub.Hello(); return View(); } } public interface IHomeHub { void Hello(); } public class HomeHub : Hub, IHomeHub { public void Hello() { Clients.All.hello(); } } 

for unit tests:

 [TestMethod] public void Index() { var mockHub = new Mock<IHomeHub>(); // Arrange HomeController controller = new HomeController(mockHub.Object); // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result); mockHub.Verify(h=>h.Hello(), Times.Once); } 
+1
source

All Articles