02 November 2011

How Do Moles Detours Work?

Moles is a dependency isolation and mocking framework.  Instead of building mock stubs for dependency injection, Moles allows the programmer to detour the call to portions of the actual dependency object.  So, how does Moles detour calls, without touching the source code?


When the compiler is executed, Moles tells it to generate a "moles assembly" for each assembly identified in the .moles files.  The moles assemblies are basically wrappers of the target assembly.  Stub and Moles types classes are created in this wrapper assembly, and each contains a set of Func< , > types properties associated with the method, property, and event objects of the target class.  Each of these Func< , > properties are pointed to the target objects, by default.

The HostType(Moles") attribute decorating the test methods ensures all calls get routed through the moles assembly.  When a moled test method executes, the Func< , > delegate may be pointed to an anonymous or other method.

Upon exiting a moled test method, the moles assembly Func< , > properties are reset to point to the original, target objects.  This prevents unit tests from leaving residual delegates in the moles assembly.

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.