Wednesday, August 1, 2012

How to add Moles to your C# project

Mocking frameworks normally do not allow you to mock static properties and methods. You can use the "Moles" to provide a mock implementation of these properties. "Moles" is a lightweight framework for test stubs and detours in .NET that is based on delegates. Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.

The example below refers to "MyName2" project, which can be downloaded from here. In this project, I will provide a mock implementation of "Name" property in "Program" class.

  • The first thing is to download and Install 64 bit version of moles from here
  • Add a reference to Microsoft.Moles.Framework assembly to the project, which is to be tested. (MyName2).
  • Add the following lines in Propeties\AssemblyInfo.cs of the main project. (MyName2)
      1. using Microsoft.Moles.Framework;
      2. [assembly: MoledType(typeof(MyName2.Program))]
  • Replace "MyName2.Program" with the class containing the static property/method that you want to mole
  • In the test project, (MyName2.Tests), right-click on the assembly that contain the class whose property you want to mole (MyName2) and click "Add Mole Assembly"

    • A file by the name of <AssemblyName>.moles will be added to your test project. (MyName2.moles)
  • Build the test project so that a mole assembly is added in reference. Its name will have ".Moles" appended to the names of the assembly that you molded. (MyName2.Moles)
  • In the C# file that you are writing unit-tests, add the following line

      1. using Microsoft.Moles.Framework;
  • In the test method you want to use mole, add the following line under [TestMethod]

      1. using Microsoft.Moles.Framework;
  • Use the moled type to provide a delegate to the static method/property (MProgram.NameGet) which will be called when a get is done on Program.Name.

The main link to Microsoft Moles is http://research.microsoft.com/en-us/projects/moles/

Blogger Labels: C#,Unit Testing,Moles

No comments: