Replacing the Current Service Locator
In this scenario, you want to provide a custom environment for unit testing. You have stub implementations of a service your component uses and you want to register the stub implementations with a service locator. This scenario may not require a full SharePoint
context at runtime.
In Visual Studio, add a reference to the SharePoint Guidance Library, Microsoft.Practices.SPG.Common.dll
. Create an instance of the
class and invoke its
method. Use the interface and the implementation class you want your application class to use at run time as type parameters to the
method. Call the ReplaceCurrentServiceLocator
static method of the
class to set the current service locator.
For an extended example of how to replace the current SharePoint service locator, see [TBD].
Replacing the Current SharePoint Service Locator
The following code shows an example of a unit testing initialization method that replaces a configured service with a test-specific class.
public class PricingFixture
private MockSecurityHelper mockSecurityHelper;
public void Init()
ActivatingServiceLocator serviceLocator = new ActivatingServiceLocator();
public void Cleanup()
It is recommended that you use ReplaceCurrentServiceLocator
to set the service locator to null as part of the unit test's cleanup step. This allows the default SharePoint service locator to be restored for subsequent tests.
Passing the InstantiationType
enumerated value as an argument to the
method allows you to specify that a single instance of the implementation class is used for all service location requests. This is important in the unit-testing scenario because you typically want to set test-specific properties of
the mock object that your test environment provides. By default, the ActivatingServiceLocator
class creates a new instance with each service location request.
Note: In the unit testing scenario, it is important to replace the current SharePoint service locator
before you attempt to get the value of the SharePointServiceLocator.Current static property. The reason for this is that instantiating the default SharePoint service locator requires you to be running in a SharePoint context, which may not be
the case when performing a unit test. By replacing the current service locator before evaluating the
SharePointServiceLocator.Current property, you can avoid a runtime dependency on the SharePoint environment.
To give feedback.
Copyright (c) 2007 by Microsoft Corporation. All rights reserved.