09 November 2011

When Do I Use a Stub or Mole Type?

Give preference to Stub types.  Using a stub type helps you adhere to sound architecture principles, when writing new code and/or using Test Driven Development (TDD).

The following is extracted from pages 3 and 4 of the Microsoft Moles Reference Manual, (© 2010 Microsoft Corporation). I take no credit for the following content.
·         Detour implementation. The mole types rely on runtime code rewriting, which is implemented by a CLR profiler. The stub types simply rely on virtual method dispatch.
·         Performance. The runtime code rewriting used by mole types introduces significant performance degradation in execution time. The stub types do not have this performance overhead and are as fast as virtual methods can go.
·         Static methods, sealed types. The stub types can only influence methods that can be overridden. Therefore, stub types cannot be used for static methods, non-virtual methods, sealed virtual methods, methods in sealed types, and so on.
·         Internal types. Both stub types and mole types can be used with internal types that were made accessible through the [InternalsVisibleTo(…)] attribute.
·         Private methods. The mole types can replace private methods if all the types on the method signature are visible.
·         Static Constructor and Finalizers. Moles can “erase” static constructors and finalizers for user given types.
·         Deployment. The mole types require a CLR profiler to be installed on the machine to execute the tests. This might be an issue if the build machine cannot be modified. The stub types are self-contained and will work properly as long as the Moles framework assemblies are present.
·         Interfaces and abstract methods. Stub types provide implementations of interfaces and abstract methods that can be used in testing. Mole types cannot instrument interfaces and abstract methods, because they do not have method bodies.
In general, we recommend that you use stub types to isolate from dependencies. This can be achieved by hiding the components behind interfaces. Mole types can be used to isolate from third-party components that do not provide a testable API.

Stub Types and Mole Types Comparison

Stub types
Mole types
Detour mechanism
Virtual method overriding
Runtime instrumentation
Static methods, sealed types
Internal types
Private methods
Static Constructors and Finalizers
Abstract methods
Microsoft Moles Reference Manual, (© 2010 Microsoft Corporation)

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.