I am back again after months of dormancy to blog about something interesting and an easy to use mocking framework for .NET assemblies, that I have learnt and used very recently. It’s about the Microsoft Moles Framework that came out as a research project PEX in Microsoft.  PEX and Moles are available as an add-on for VS 2010. [However, with VS 2012, they are being replaced with Fakes and would be packaged along with VS 2012 ultimate version] So long I was aware of only doing an integration unit testing by executing the entire method to be tested by just doing a data setup and validate the actual and expected result upon execution of the test. The project I work currently doesn’t support this, as the code interacts with a lot of third party modules for which there are no testable APIs available. That’s when I got to learn about this Moles. This post is just about the introduction and various basic concepts around Moles framework which one should be aware before jumpstarting Moles usage in the Unit tests.

What is Moles Framework?

Moles is a mocking framework for isolation unit testing, with which you can mock any static, sealed/non-sealed, public/private/protected methods, properties, events, and de-tour method calls to perform isolation unit testing.  For example, if the method being tested is dependent on methods from external assemblies or built in framework assemblies, it gets tougher to test your piece of code in isolation. Moles give us a helping hand in such situation to mock all other external dependent entities and isolate your code alone to be tested.

What it offers?

      Moles framework provides two ways to mock the objects, viz., Stubs and Moles.

Stubs -> Stubs can be used on interfaces, abstract classes, non-sealed classes which exposes virtual methods. Stubs rewrite the methods by virtual method overriding. The stubbed type will be named as follows “S<StubbedType>” e.g., Class TestClass will be stubbed to STestClass

Moles -> Moles can be used on static classes, and methods and classes from external assemblies where you don’t have control. Moles use CLR profiler and do the run time instrumentation. Test methods which uses Moles run under a separate Moles process “Microsoft.Moles.vsHost.x86.exe*32“. The moled type will be named as follows “M<MoledType>“e.g., Class TestClass will be moled to MTestClass

Using Stubs for Mocking:

  1. When working with interfaces, you can use the Stub implementation of the interface and run the unit test with the stubs. Unit test methods which are using Stubs run under the normal unit test hosting process.
  2. Stubs would be of greater use, if the application follows “Code to interface and not implementation” design principle, as it eases dependency injection.
  3. The Stubbed classes which Moles create would inherit the actual class, and implement the interfaces IStub, IPartialStub, IBehaved available in “Microsoft.Moles.Framework.dll”

Sample screenshot of a Stubbed class below:

Stubbed Class

Important properties of Stubs to be aware of:

  • CallBase – This is to specify, whether to call the actual implementation of the stubbed class, Default is ‘False‘ which means the stubbed implementation would be used. Setting this to ‘True’, would invoke the actual implementation and not the mocked one. This property would be available only while stubbing classes.
  • InstanceBehaviour – This is to specify, what should be the default behavior of this stub. When the stub is not implemented properly but invoked, “StubNotImplementedException” would be thrown, however this can be changed by modifying this property to the built in behaviors available in “Microsoft.Moles.Framework.dll”.

The table below shows the built in behaviors

BehavedBehaviors.DefaultValue Will return the default value of the type when not stubbed.
BehavedBehaviors.NotImplemented Will throw StubNotImplementedException

However any custom behaviors can be created by implementing “IBehavior” interface present under “Microsoft.Moles.Framework.Behaviors” namespace.

Using Moles for Mocking:

  • When working with Static methods of any assemblies or more importantly the framework assemblies, Moles can be used to mock. e.g., this could be of greater importance on unit testing the data access layer, where you can mock the behavior of “System.Data.dll” and can perform the isolation testing of the data access layer methods.
  • You can either specify the moled behavior for a specific instance by passing the actual instance to the moled type or by using the AllInstances property of the Moled type. This will make sure for ALL the instances of the moled type; the mocked behavior will be executed.
  • The moled types are all inherited from “MoleBase<T>

Sample screenshot of a moled type:

Moled Type

A small tabular comparison and the recommendation of usage between Moles and Stubs, which I have come up with, based on my understanding of the moles framework is given below

Moles Vs Stubs

Per recommended best practices by Microsoft, use Stubs where ever it is possible and use Moles if and only if Stubs don’t help.

Getting started with Moles:

Moles framework for VS 2010 can be downloaded from visual studio gallery. Once installed, you will get “Add Moles Assembly” on right clicking any of the dlls (which you want to mole) under the references section of your project.This will add “<ReferencedAssembly>.Moles” xml file under your project. Building the unit test project will add “<ReferencedAssembly>.Moles dll” which gives the Stubs and Moles for all the types present in the dll.

image       image

Moles will generate delegates (Func<T1…Tn, Tresult>) for all the methods with the method name suffixed with all the parameters it takes which can be used to mock the behavior. e.g. Mocking the Enterprise library 5.0’s Logging component’s write method, yielded a delegate for

public static void Write(object message, string category)

as shown in screenshot below, to which you can attach any behavior you wish.

Moled Delegate

As a last and important note, remember always to attribute the test methods that contains the Moled implementation with HostType(“Moles”). as they all run under the process(“Microsoft.Moles.vsHost.x86.exe*32“), Failing this, would result in an exception as shown below being thrown

Moles requires tests to be IN an instrumented process.

In Visual Studio Unit Test, add the following attribute to your unit test method:

        [TestMethod]

        [HostType(“Moles”)] // add this attribute

        public void Test()

        { … }

Extensions are also available for most unit test frameworks. Please refer to the Moles manual.

That’s it; you are all set to mock the implementation of any method of your interest!!! Pretty easy isn’t it??

Glad that you had resisted yourself so much with the theory and reached till here 🙂 More code samples on using Moles and Stubs is underway and would be available very sooner in my next post.

Appreciate the reader’s comments and feedback to improve the blog further.