Click here to Skip to main content
12,821,315 members (34,549 online)
Click here to Skip to main content
Add your own
alternative version


4 bookmarked
Posted 5 Aug 2010

Mocking the Unmockable: Using Microsoft Moles with Gallio

, 5 Aug 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
CodeProjectUpdate 29/04/10:In contrary to what I initially stated in this post, Moles is not only available as part of the Pex framework, but also stand-alone on Visual Studio Gallery, and this is completely free (no MSDN subscription required). - Thanks to Peli for the correction...

Update 29/04/10:

In contrary to what I initially stated in this post, Moles is not only available as part of the Pex framework, but also stand-alone on Visual Studio Gallery, and this is completely free (no MSDN subscription required). - Thanks to Peli for the correction...

Usual opensource mocking frameworks (like e.g. Moq or Rhino.Mocks) can mock only interfaces and virtual methods. In contrary to that, Microsoft’s Moles framework can ‘mock’ virtually anything, in that it uses runtime instrumentation to inject callbacks in the method MSIL bodies of the moled methods. Therefore, it is possible to detour any .NET method, including non-virtual/static methods in sealed types. This can be extremely helpful when dealing e.g. with code that calls into the .NET framework, some third-party or legacy stuff etc…

Some useful collected resources (links to website, documentation material and some videos) can be found in my toolbox on Delicious under this link:

A Gallio extension for Moles

Originally, Moles is a part of Microsoft’s Pex framework and thus integrates best with Visual Studio Unit Tests (MSTest). However, the Moles sample download contains some additional assemblies to also support other unit test frameworks. They provide a Moled attribute to ease the usage of mole types with the respective framework (there are extensions for NUnit, and MbUnit v2 included with the samples). As there is no such extension for the Gallio platform, I did the few required lines myself – the resulting Gallio.Moles.dll is included with the sample download.

With this little assembly in place, it is possible to use Moles with Gallio like that:

[Test, Moled]

public void SomeTest()



What you can do with it

Moles can be very helpful, if you need to ‘mock’ something other than a virtual or interface-implementing method. This might be the case when dealing with some third-party component, legacy code, or if you want to ‘mock’ the .NET framework itself.

Generally, you need to announce each moled type that you want to use in a test with the MoledType attribute on assembly level. For example:

[assembly: MoledType(typeof(System.IO.File))]

Below are some typical use cases for Moles. For a more detailed overview (incl. naming conventions and an instruction on how to create the required moles assemblies), please refer to the reference material above.

Detouring the .NET framework

Imagine that you want to test a method similar to the one below, which internally calls some framework method:

public void ReadFileContent(string fileName)


    this.FileContent = System.IO.File.ReadAllText(fileName);


Using a mole, you would replace the call to the File.ReadAllText(string) method with a runtime delegate like so:

[Test, Moled]

[Description("This 'mocks' the System.IO.File class with a custom delegate.")]

public void ReadFileContentWithMoles()


    // arrange ('mock' the FileSystem with a delegate)

    System.IO.Moles.MFile.ReadAllTextString = 

        (fname => fname == FileName ? FileContent : "WrongFileName");


    // act 

    var testTarget = new TestTarget.TestTarget();



    // assert 

    Assert.AreEqual(FileContent, testTarget.FileContent);


Detouring static methods and/or classes

A static method like the below…

public static string StaticMethod(int x, int y) { return string.Format("{0}{1}", x, y); }
<p>… can be ‘mocked’ with the following:</p>

Detouring constructors

You can do this delegate thing even with a class’ constructor. The syntax for this is not all too intuitive, because you have to setup the internal state of the mole, but generally it works like a charm. For example, to replace this c’tor…

public class ClassWithCtor


    public int Value { get; private set; }


    public ClassWithCtor(int someValue)


        this.Value = someValue;



… you would do the following:

[Test, Moled]

public void ConstructorTestWithMoles()


    MClassWithCtor.ConstructorInt32 =

           ((@class, @value) => new MClassWithCtor(@class) {ValueGet = () => 99});


    var classWithCtor = new ClassWithCtor(3);


    Assert.AreEqual(99, classWithCtor.Value);


Detouring abstract base classes

You can also use this approach to ‘mock’ abstract base classes of a class that you call in your test. Assumed that you have something like that:

public abstract class AbstractBaseClass


    public virtual string SaySomething()


        return "Hello from base.";




public class ChildClass : AbstractBaseClass


    public override string SaySomething()


        return string.Format(

            "Hello from child. Base says: '{0}'", 




Then you would set up the child’s underlying base class like this:

[Test, Moled]

public void AbstractBaseClassTestWithMoles()


    ChildClass child = new ChildClass();

    new MAbstractBaseClass(child)


                SaySomething = () => "Leave me alone!"


        .InstanceBehavior = MoleBehaviors.Fallthrough;


    var hello = child.SaySomething();


    Assert.AreEqual("Hello from child. Base says: 'Leave me alone!'", hello);


Setting the moles behavior to a value of MoleBehaviors.Fallthrough causes the ‘original’ method to be called if a respective delegate is not provided explicitly – here it causes the ChildClass’ override of the SaySomething() method to be called.

There are some more possible scenarios, where the Moles framework could be of much help (e.g. it’s also possible to detour interface implementations like IEnumerable<T> and such…). One other possibility that comes to my mind (because I’m currently dealing with that), is to replace calls from repository classes to the ADO.NET Entity Framework O/R mapper with delegates to isolate the repository classes from the underlying database, which otherwise would not be possible…


Since Moles relies on runtime instrumentation, mole types must be run under the Pex profiler. This only works from inside Visual Studio if you write your tests with MSTest (Visual Studio Unit Test). While other unit test frameworks generally can be used with Moles, they require the respective tests to be run via command line, executed through the moles.runner.exe tool. A typical test execution would be similar to this:

moles.runner.exe <mytests.dll> /runner:<myframework.console.exe> /args:/<myargs>
<p>So, the moled test can be run through tools like <a href="">NCover</a>


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Thomas Weller
Software Developer (Senior) Freelancer
Germany Germany
I'm a freelance software developer/architect located in Southern Germany with 10+ years of experience in C++, VB, and C# software projects. In the last few years I do all my coding exclusively in C#.
I am especially dedicated to Test-driven development, OO architecture, and software quality assurance issues and tools.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 5 Aug 2010
Article Copyright 2010 by Thomas Weller
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid