22 October 2011

How do I make my test use Moles?

NOTE: The Moles isolation framework must be installed to any machine that will compile the solution and/or execute the mole tests.

The following things must be done, to use Moles in a test.  This looks like a lot, now.  However, you'll quickly get the hang of things, and have these steps done in seconds!  Using my CodeRush Moles templates will help speed things up.

  1. Add a mole assembly for the assemblies requring call detours
  2. Add a mole assembly for mscorlib, if needed (see How Do I Mole .NET Framework Types?)
  3. Compile the solution, to generate the mole assemblies
  4. Add using declarations:
    1. using Microsoft.VisualStudio.TestTools.UnitTesting;
      (Pretty much standard)
    2. using Microsoft.Moles.Framework; (Moles framework support)
    3. using YourProjectNamespace.Moles; (The moled assembly for your project -- replace YourProjectNamespace with your project's namespace)
    4. Add any moled .NET framework assembly using declarations, ending in .Moles.
  5. For each moled .NET type, add a MoledType assembly attribute, immediately after the using declarations.  Failure to add requisite attributes causes the compiler to display an error, which provides guidance on adding the attribute.  Check out my CodeRush Templates for Moles, to quickly insert these attributes!


    NOTE: Avoid using MolesAssembly, unless you are using the majority of the moled types in the assembly.  The Moles Framework will only prime the types identified by MoledType, but primes all types of the assembly, when using MoledAssembly.
  6. All test methods that call one or more moled types must be decorated with the HostType attribute:
    NOTE: The HostType attribute must be added to test methods that call another method containing calls to moled types!  This is true, even when the test method does not directly contain calls to mole types.
You're ready to go!  Here's a sample test class:
    using System;
    using System.IO;
    using System.IO.Moles;
    using Microsoft.Moles.Framework;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using PexMolesSampleProject;
    using PexMolesSampleProject.Moles;
    namespace PexMolesSampleProject.Test
        public class Class3Test
            public void Class3Test_SetsFileSystemField()
                MFile.DeleteString = i => { };
                MClass1.ToUpperString = lowerCase => lowerCase.ToUpper();

    No comments:

    Post a Comment

    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.