Unitesting
Unitesting
You can use the unit test features in SignalR 2.0 to create unit tests for your SignalR application. SignalR 2.0 includes the IHubCallerConnectionContext interface, which can be used to create a mock object to simulate your hub methods for testing. In this section, you'll add unit tests for the application created in the Getting Started tutorial using XUnit.net andMoq. XUnit.net will be used to control the test; Moq will be used to create a mock object for testing. Other mocking frameworks can be used if desired; NSubstitute is also a good choice. This tutorial demonstrates how to set up the mock object in two ways: First, using a dynamic object (introduced in .NET Framework 4), and second, using an interface.
Contents
This tutorial contains the following sections. Unit testing with Dynamic Unit testing by type
namespace TestLibrary { public class Tests { [Fact] public void HubsAreMockableViaDynamic() { bool sendCalled = false; var hub = new ChatHub();
var mockClients = new Mock<IHubCallerConnectionContext>(); hub.Clients = mockClients.Object; dynamic all = new ExpandoObject(); all.broadcastMessage = new Action<string, string>((name, message) => { sendCalled = true; }); mockClients.Setup(m => m.All).Returns((ExpandoObject)all); hub.Send("TestUser", "TestMessage"); Assert.True(sendCalled); } } }
1.
In the code above, a test client is created using the Mock object from the Moq library, of typeIHubCallerConnectionContext. The IHubCallerConnectionContext interface is the proxy object with which you invoke methods on the client. The broadcastMessage function is then defined for the mock client so that it can be called by the ChatHub class. The test engine then calls the Send method of the ChatHub class, which in turn calls the mocked broadcastMessage function. Build the solution by pressing F6. Run the unit test. In Visual Studio, select Test, Windows, Test
2. 3.
Explorer. In the Test Explorer window, right-click HubsAreMockableViaDynamic and select Run Selected Tests.
18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. }
[Fact] public void HubsAreMockableViaType() { var hub = new ChatHub(); var mockClients = new Mock<IHubCallerConnectionContext>(); var all = new Mock<IClientContract>(); hub.Clients = mockClients.Object; all.Setup(m => m.broadcastMessage(It.IsAny<string>(), It.IsAny<string>())).Verifiable(); mockClients.Setup(m => m.All).Returns(all.Object); hub.Send("TestUser", "TestMessage"); all.VerifyAll(); } }
In the code above, an interface is created defining the signature of the broadcastMessage method for which the test engine will create a mock client. A mock client is then created using the Mock object, of typeIHubCallerConnectionContext. The IHubCallerConnectionContext interface is the proxy object with which you invoke methods on the client. The test then creates an instance of ChatHub, and then creates a mock version of the broadcastMessagemethod, which in turn is invoked by calling the Send method on the hub. 33. Build the solution by pressing F6. 34. Run the unit test. In Visual Studio, select Test, Windows, Test Explorer. In the Test Explorer window, right-click HubsAreMockableViaDynamic and select Run Selected Tests.
Dependency injection is a way to remove hard-coded dependencies between objects, making it easier to replace an object's dependencies, either for testing (using mock objects) or to change run-time behavior. This tutorial shows how to perform dependency injection on SignalR hubs. It also shows how to use IoC containers with SignalR. An IoC container is a general framework for dependency injection.
// Without dependency injection. class SomeComponent { ILogger _logger = new FileLogger(@"C:\logs\log.txt"); public void DoSomething() { _logger.LogMessage("DoSomething"); } } This works, but its not the best design. If you want to replace FileLogger with another ILogger implementation, you will have to modify SomeComponent. Supposing that a lot of other objects use FileLogger, you will need to change all of them. Or if you decide to make FileLogger a singleton, youll also need to make changes throughout the application. A better approach is to inject an ILogger into the objectfor example, by using a constructor argument: // With dependency injection. class SomeComponent { ILogger _logger; // Inject ILogger into the object. public SomeComponent(ILogger logger) { if (logger == null) { throw new NullReferenceException("logger"); } _logger = logger; } public void DoSomething() { _logger.LogMessage("DoSomething"); } } Now the object is not responsible for selecting which ILogger to use. You can swich ILogger implementations without changing the objects that depend on it. var logger = new TraceLogger(@"C:\logs\log.etl"); var someComponent = new SomeComponent(logger); This pattern is called constructor injection. Another pattern is setter injection, where you set the dependency through a setter method or property.
Consider the Chat application from the tutorial Getting Started with SignalR 2.0. Here is the hub class from that application: public class ChatHub : Hub { public void Send(string name, string message) { Clients.All.addMessage(name, message); } } Suppose that you want to store chat messages on the server before sending them. You might define an interface that abstracts this functionality, and use DI to inject the interface into the ChatHub class. public interface IChatRepository { void Add(string name, string message); // Other methods not shown. } public class ChatHub : Hub { private IChatRepository _repository; public ChatHub(IChatRepository repository) { _repository = repository; } public void Send(string name, string message) { _repository.Add(name, message); Clients.All.addMessage(name, message); } The only problem is that a SignalR application does not directly create hubs; SignalR creates them for you. By default, SignalR expects a hub class to have a parameterless constructor. However, you can easily register a function to create hub instances, and use this function to perform DI. Register the function by callingGlobalHost.DependencyResolver.Register. public void Configuration(IAppBuilder app) { GlobalHost.DependencyResolver.Register( typeof(ChatHub), () => new ChatHub(new ChatMessageRepository())); App.MapSignalR(); // ... }
Now SignalR will invoke this anonymous function whenever it needs to create a ChatHub instance.
IoC Containers
The previous code is fine for simple cases. But you still had to write this: ... new ChatHub(new ChatMessageRepository()) ... In a complex application with many dependencies, you might need to write a lot of this wiring code. This code can be hard to maintain, especially if dependencies are nested. It is also hard to unit test. One solution is to use an IoC container. An IoC container is a software component that is responsible for managing dependencies.You register types with the container, and then use the container to create objects. The container automatically figures out the dependency relations. Many IoC containers also allow you to control things like object lifetime and scope. Note: IoC stands for inversion of control, which is a gener al pattern where a framework calls into application code. An IoC container constructs your objects for you, which inverts the usual flow of control.
throw new ArgumentNullException("stockTicker"); } _stockTicker = stockTicker; } // ... For StockTicker, remove the singleton instance. Later, we'll use the IoC container to control the StockTicker lifetime. Also, make the constructor public. public class StockTicker { //private readonly static Lazy<StockTicker> _instance = new Lazy<StockTicker>( // () => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients)); // Important! Make this constructor public. public StockTicker(IHubConnectionContext clients) { if (clients == null) { throw new ArgumentNullException("clients"); } Clients = clients; LoadDefaultStocks(); } //public static StockTicker Instance //{ // get // { // return _instance.Value; // } //} Next, we can refactor the code by creating an interface for StockTicker. Well use this interface to decouple theStockTickerHub from the StockTicker class. Visual Studio makes this kind of refactoring easy. Open the file StockTicker.cs, right-click on the StockTicker class declaration, and select Refactor ... Extract Interface.
In the Extract Interface dialog, click Select All. Leave the other defaults. Click OK.
Visual Studio creates a new interface named IStockTicker, and also changes StockTicker to derive fromIStockTicker. Open the file IStockTicker.cs and change the interface to public. public interface IStockTicker { void CloseMarket(); IEnumerable<Stock> GetAllStocks(); MarketState MarketState { get; } void OpenMarket(); void Reset(); } In the StockTickerHub class, change the two instances of StockTicker to IStockTicker:
[HubName("stockTicker")] public class StockTickerHub : Hub { private readonly IStockTicker _stockTicker; public StockTickerHub(IStockTicker stockTicker) { if (stockTicker == null) { throw new ArgumentNullException("stockTicker"); } _stockTicker = stockTicker; } Creating an IStockTicker interface isnt strictly necessary, but I wanted to show how DI can help to reduce coupling between components in your application.
This class overrides the GetService and GetServices methods of DefaultDependencyResolver. SignalR calls these methods to create various objects at runtime, including hub instances, as well as various services used internally by SignalR. The GetService method creates a single instance of a type. Override this method to call the Ninject kernel'sTryGet method. If that method returns null, fall back to the default resolver. The GetServices method creates a collection of objects of a specified type. Override this method to concatenate the results from Ninject with the results from the default resolver.
This code is saying two things. First, whenever the application needs an IStockTicker, the kernel should create an instance of StockTicker. Second, the StockTicker class should be a created as a singleton object. Ninject will create one instance of the object, and return the same instance for each request. Create a binding for IHubConnectionContext as follows: kernel.Bind<IHubConnectionContext>().ToMethod(context => resolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients ).WhenInjectedInto<IStockTicker>(); This code creatres an anonymous function that returns an IHubConnection. The WhenInjectedInto method tells Ninject to use this function only when creating IStockTicker instances. The reason is that SignalR creates IHubConnectionContext instances internally, and we don't want to override how SignalR creates them. This function only applies to our StockTicker class. Pass the dependency resolver into the MapSignalR method: App.MapSignalR(config); Now SignalR will use the resolver specified in MapSignalR, instead of the default resolver. Here is the complete code listing for RegisterHubs.Start. public static class RegisterHubs { public static void Start() { var kernel = new StandardKernel();
var resolver = new NinjectSignalRDependencyResolver(kernel); kernel.Bind<IStockTicker>() .To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>() .InSingletonScope(); kernel.Bind<IHubConnectionContext>().ToMethod(context => resolver.Resolve<IConnectionManager>(). GetHubContext<StockTickerHub>().Clients ).WhenInjectedInto<IStockTicker>(); var config = new HubConfiguration() { Resolver = resolver }; App.MapSignalR(config); } } To run the StockTicker application in Visual Studio, press F5. In the browser window, navigate to http://localhost:port/SignalR.Sample/StockTicker.html.