Mocks & Stubs

Mocks provide an execution context wherein a given member (property or method) of a known object is overridden with a temporary substitute. When invoked, the mocked value will be available in the scope of the function delegate that is passed into the mock. After the delegate completes execution, the mock is cleaned up, and the member is reverted to its previous state. Mocks are useful for injecting code dependencies and stub implementations, and help to identify and isolate boundary crossing events when designing production code. The global object, typically the host engine (i.e., the top level this; in the case of a browser, roughly analogous to the window object reference) is available at any depth as the result of the method Object.Global(). So, to, e.g., mock window.open(), we could override the window reference on the host engine: function OverridesWindowOpenMethod(){ // Arrange var mockWindow=Mocks.GetMock(Object.Global(),"window",{open:function(targetUrl){ actual=targetUrl; }}); var expected="expected"; var actual=null; //Act mockWindow(function(){ window.open(expected); }) //Assert Assert.Equal(expected,atual); }

Stubs are an instrumented object mapping system, for creating complex hierarchies, interfaces, and object shapes to meet the expectations of production APIs. The instrumentation automatically captures invocations of stub methods, arguments supplied, and provides well-known return values, which can be easily changed as the test requires. Thus, the above fact could be rewritten thusly: function OverridesWindowOpenMethod(){ // Arrange var stubWindow=Stubs.GetObject({open:{parameters:["targetUrl"]}}); var expected="expected"; var actual=null; //Act stubWindow.open(expected); actual=stubWindow.open.Calls[0].Arguments.targetUrl; //Assert Assert.Equal(expected,atual); }

Mocks and Stubs are frequently used together, and can be used to provide complex, host-specific environments, such as a DOM implementation, or a database or server abstraction.