Setting it upEdit

After install Pex,

  1. Create a unit test project in Visual Studio, and add a Reference to Microsoft.Pex.Framework, which will be listed in the .NET tab of the Add Reference dialog
  2. To the test project, Add / New Item and select "Stubs and Moles for Testing".
  3. Name the file ClassLibrary1.stubx, where "ClassLibrary1" is the name of the assembly under test.
  4. Edit the .stubx file and change the value of the Name attribute of the Assembly tag to the name of your assembly (eg. ClassLibrary1)
  5. Add using statement to the top of the test class file. Example:
using ClassLibrary1.Stubs;

Stubbing a methodEdit

Say we want implement a stub for ISearch, defined as:

   public interface ISearch
       string Locate( string token );

in the assembly under test.

In the test, let's say we want to create a stub where Locate simply returns a trimmed version of the passed in token. The stub can be created as:

   var stubISearch = new SISearch();
   stubISearch.LocateString = delegate(string token)
       return token.Trim();

Or, the delegate can be succinctly assigned using lambda notation:

   stubISearch.LocateString = token => token.Trim();

The stub can now be used wherever an ISearch implementation is needed. Example:

   ISearch search = stubISearch;
   Assert.AreEqual("blah", search.Locate("  blah   "));

Stubbing a propertyEdit

Assming the above ISearch interface has a property:

   int Magic { get; set; }

It can be stubbed like so:

   int magic = 42;
    stubISearch.MagicGet = () => magic;
    stubISearch.MagicSetInt32 = (value) => magic = value;
Community content is available under CC-BY-SA unless otherwise noted.