Mocking SignalR hub object

Skip to first unread message

Patrick Fletcher

Jan 6, 2014, 5:49:16 PM1/6/14
I'm trying to create a unit test for a SignalR application (the one created in the Getting Started tutorial hereusing Moq and XUnit. 

Some of the hub's functionality- the broadcastMessage method- is defined in the Javascript client. How do I set up the mock client object? Here's what I've got so far:

using System;
using Xunit;
using SignalRChat;
using Microsoft.AspNet.SignalR.Hubs;
using Moq;
using System.Dynamic;

namespace TestLibrary
    public class Tests
        public void HubsAreMockableViaDynamic()
            bool sendCalled = false;
            var hub = new ChatHub();
            var mockClients = new Mock<IHubCallerConnectionContext>();
            hub.Clients = mockClients.Object;
            dynamic all = new ExpandoObject();
            all.send = new Action<string>(message =>
                sendCalled = true;
            mockClients.Setup(m => m.All).Returns((ExpandoObject)all);
            hub.Send("TestUser", "TestMessage");
Here's the result:
C:\Projects\SignalRChat\TestLibrary\bin\Debug>xunit.console.clr4 TestLibrary.dll console test runner (64-bit .NET 4.0.30319.34003)
Copyright (C) 2013 Outercurve Foundation.

xunit.dll:     Version
Test assembly: C:\Projects\SignalRChat\TestLibrary\bin\Debug\TestLibrary.dll

TestLibrary.Tests.HubsAreMockableViaDynamic [FAIL]
   Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'System.Dynamic.Expan
doObject' does not contain a definition for 'broadcastMessage'
   Stack Trace:
      at CallSite.Target(Closure , CallSite , Object , String , String )
      at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite
 site, T0 arg0, T1 arg1, T2 arg2)
      c:\Projects\SignalRChat\SignalRChat\ChatHub.cs(11,0): at SignalRChat.ChatH
ub.Send(String name, String message)
      c:\Projects\SignalRChat\TestLibrary\Tests.cs(31,0): at TestLibrary.Tests.H

1 total, 1 failed, 0 skipped, took 1.371 seconds

Daniel Cazzulino

Jan 6, 2014, 5:55:39 PM1/6/14
to moqdisc
Maybe a good place to start would be SignalR tests themselves? They use Moq too... 


Daniel Cazzulino

You received this message because you are subscribed to the Google Groups "Moq Discussions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
For more options, visit

Reply all
Reply to author
0 new messages