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.
source share