11 October 2011

How do I Mole an Assembly?

Creating a Moles wrapper assembly ("moled" assembly) has been greatly simplified:
  1. Expand the test project node, in the Solution Explorer window
  2. Expand the References child node
  3. Right-click the assembly you wish to mole -- the context menu appears
  4. In the context menu, select the Add Moles Assembly option -- a .moles file appears in the text project
  5. Build the test project
Before building the test project, you should see a new file appear in the test project, named (TargetAssemblyName).moles.  This file tells the compiler that in needs to create a mole assembly for the specified target assembly.  After the build, you will see the mole assembly appear in the references node.  This will be named after the target assembly, but affixed with ".moles".

It is important to remember that you must add the appropriate using statements and assembly attribute, to access the Moles framework from your unit tests:

using Microsoft.Moles.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MolesDemos;
using MolesDemos.Moles;
[assemblyMoledType(typeof(IMolesDemoClass))]

Also, test methods using Moles must be decorated with the HostType attribute:

[TestMethod]
[HostType("Moles")]
[ExpectedException(typeof(FileNotFoundException))]
public void MyMoleTestMethod()
{
    ...    
}


NOTE:  After adding objects to the target code, it may be necessary to perform a rebuild on the test project.  It things really get stuck:
  1. Clean both the target and test projects
  2. Delete the hidden "Moled Assemblies" folder and contents
  3. Rebuilt the target project
  4. Rebuild the test project

3 comments:

  1. How do we mole the system assembly

    ReplyDelete
  2. To mole the System assembly (.NET Framework):

    1. Right-click the References node of your test project. In the context menu, select "Add Moles Assembly for mscorlib". This allows you to detour the .NET Framework namespaces.

    2. Add the using declaration for the mole assembly you wish to use. For example, to detour System.StringComparer, add declaration:
    using System.Moles;

    3. Compile the project.

    4. Detour the method, in a moled test method. This detour always returns 0 (equal):

    System.Moles.MStringComparer.AllInstances.CompareObjectObject = (instance, lhs, rhs) => 0;

    ReplyDelete

Please provide details, when posting technical comments. If you find an error in sample code or have found bad information/misinformation in a post, please e-mail me details, so I can make corrections as quickly as possible.