09 November 2011

How Do I Write a Detour?

If you don't use lambda expressions, take a couple of hours right now to learn it, and vastly improve your skill set.  I can wait...

Now that we all know lambda expressions are simple delegates set to "super easy" mode, you already know how to write a detour!  Detours are set the same way in both stub and mole types.  You have two options, when detouring a call to a stub or moles type member.

Granted, these code examples are very simplistic, but you can use these to your advantage. See the Tricks With Detours section of the Testing With Microsoft Pex and Moles page, for some ideas.
METHOD #1: Create an anonymous method inside the lambda expression (good for one-time uses)
[HostType("Moles")]
[TestMethod]
public void Test()
{
    // Always return true.
    System.IO.Moles.MFile.ExistsString = path => true;
}


METHOD #2: Identify a different method (great for repeat usage)
private bool ReturnTrue()
{
    return true;
}
 
[HostType("Moles")]
[TestMethod]
public void Test()
{
    // Call a different methos.
    System.IO.Moles.MFile.ExistsString = path => ReturnTrue();
}

See Also:

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.