Customizing the Logger for Unit Testing
Typical Goals
In this scenario, you want to bypass the default logging and tracing behavior of the SharePoint logger and write all logging and tracing information to a mock logger that is specified by your unit test.
Solution
In Visual Studio, add a reference to the SharePoint Guidance Library, Microsoft.Practices.SPG.Common.dll. Create a mock implementation of the ILogger interface. This mock logger can write to the standard output or to a test-provided file stream, or simply set a public property that shows that the logger was invoked as expected. When you initialize your unit test, replace the current SharePoint service locator with a test-provided service locator that includes a type mapping to your mock logger. Run your unit test. For information about replacing the service locator, see The SharePoint Service Locator.
Customizing the Logger for Unit Testing
public class MyFixture
{
private MockLogger logger;
[TestInitialize]
public void TestInitialize()
{
ActivatingServiceLocator locator = new ActivatingServiceLocator();
locator.RegisterTypeMapping<ILogger, MockLogger>
(InstantiationType.AsSingleton);
SharePointServiceLocator.ReplaceCurrentServiceLocator(locator);
this.logger =
SharePointServiceLocator.Current.GetInstance<ILogger>()
as MockLogger;
}
// ...
}
In this test initialization method, the current service locator instance is configured so that an instance of the MockLogger class is returned when the SharePoint service locator asks for an ILogger object. After this class is registered with the service locator, the logging output for any objects that use ILogger are directed to the test-provided logging implementation. Notice that you did not need to alter any code in the component that is being tested.
Usage Notes
To implement this scenario, you must provide a mock implementation of ILogger. The following code shows an example implementation.
public class MockLogger : ILogger
{
// Define a public property for the message.
// The unit tests can use this to validate that the method
// was called.
public string LogToOperationsCalledWithMessage {get; set;};
public void LogToOperations (string message)
{
LogToOperationsCalledWithMessage = message;
}
}