Best Practices for Stubs and Moles

When you work with the Moles framework, it is important to understand when you should use stub types and when you should use mole types. The following guidelines apply to the majority of test scenarios:

  • Use stub types (or an alternative mocking framework) and hand-coded mock classes for replacing components you control.
  • Use mole types (or an alternative detouring framework) for mocking static methods and classes that you do not control, such as SharePoint classes. Do not use mole types to implement interfaces, abstract classes, or virtual methods that you can easily mock using stub types.
  • Structure your unit tests into areas of Arrange, Act, and Assert for clarity:
    • Put the setup and configuration tasks for your test in the Arrange section.
    • Perform the actions that you want to test in the Act section.
    • Verify the results of your actions in the Assert section.
  • Test a single behavior in your unit test. If you have branching logic in your unit test, it is often a good indicator that you should have more tests.
  • Assert multiple results when it makes sense to do so. Often, a single behavior can result in multiple changes in state.
  • Use the SharePoint Service Locator, or an alternative implementation of the service location pattern, to decouple your classes from dependencies and to substitute interface implementations for unit testing.

Undoubtedly, you will encounter scenarios in which these guidelines do not apply. For example, suppose you create a class that derives from a base class that you do not own. In this case, it may be difficult to get full test coverage through the use of only simple mocking techniques. You can sometimes avoid this problem by adding virtual methods that you can override in a test implementation, but in other cases, you will need to create detours for your own methods through Moles or TypeMock.

There are many more sophisticated examples that illustrate the use of stub types, manual mocks, and mole types in the SharePoint Guidance Library and the accompanying reference implementations.