Moles are another Visual Studio add-in along with Pex. We already discussed about Pex, how to create Unit test using Pex and Parameterized Unit tests in another article.
We
already discussed about Pex and how to generate Unit Test. In this article we will discuss
about Moles and how to use moles for mock or delegate a method and property.
Install Moles from http://research.microsoft.com/en-us/projects/moles/
Create Mole
For using Moles, first we need to create the Moles of an
assembly. Add the assembly as a reference to your test project. Right click on
the assembly under References and select Add Moles Assembly.

This will add the following files and references to your
project.

Now we can mock any classes, methods & properties inside
this assembly.
Mock or delegate a Property
In our sample, the SampleClass contains a Dictionary
property.
public class SampleClass1
{
public Dictionary<string, string> Data
{
get;
set;
}
…………………………………………………….
…………………………………………………….
}
For passing meaningful data to our parameterized test, we
need to mock the dictionary and pass custom dictionary to it. We can mock it
using
Dictionary<string, string> dummy=new Dictionary<string,string>();
dummy.Add("var","value");
SampleApp.Moles.MSampleClass1.AllInstances.DataGet = ((b) => dummy);
All instances of SampleClass1 will receive the data specified to the Mole class.
As we noticed, after adding the assembly Mole, we will receive a new class with name prefixed with M. All mock operations will be performed using this new Mole class.
Mock A Method
In our SampleClass, we have a method, which returns some value.
public string GetDetails(string data)
{
---------------------------
----------------------------
return Data.First().Value;
}
For mocking the same,
SampleApp.Moles.MSampleClass1.AllInstances.GetDetailsString =((a,b) => "Dummy Data");
Here, ‘a’ refers the class instance and ‘b’ is the argument.
Conclusion
Pex and Moles are Visual Studio Add-ins for supporting the Unit test Framework. We will explore more on Pex and Moles in next article.