How to: Customize the Logger for Unit Testing

The following procedure demonstrates how to bypass the default logging and tracing behavior of the SharePoint logger and write all logging and tracing information to a mock logger. This is typically done for unit testing.

To create a mock logger

  1. In Visual Studio, add a reference to the SharePoint Guidance Library, Microsoft.Practices.SPG.Common.dll. If you are writing a feature receiver, item event receiver, workflow, or anything else that needs to be in the global assembly cache, the Microsoft.Practices.SPG.Common assembly also needs to be in the global assembly cache.

  2. Create a mock implementation of the ILogger interface. This mock logger can write to the standard output, to a test-provided file stream, or simply set a public property.

  3. When you initialize your unit test, replace the current SharePoint service locator with a test-provided service locator that includes type mappings to your mock logger. (For information about replacing the service locator, see The SharePoint Service Locator.) The following code shows how to do this.

    public class MyFixture
    {
       private MockLogger mockLogger;
    
       [TestInitialize]
       public void TestInitialize()
       {
           ActivatingServiceLocator locator = new ActivatingServiceLocator();
    
           locator.RegisterTypeMapping<ILogger, MockLogger>
                                                        (InstantiationType.AsSingleton);
    
           SharePointServiceLocator.ReplaceCurrentServiceLocator(locator);
    
           this.mockLogger =  
                SharePointServiceLocator.Current.GetInstance<ILogger>()                                                                                                                                       
                                                                                                                                           as MockLogger;
        }
    
        // ...
    }
    
  4. Run the unit test and validate that the business logic interacts with the mock logger as expected. The following code shows how to do this.

    [TestMethod]
    public void OrderProcesserLogs()
    {
    
       // Arrange
       this.mockLogger.LogToOperationsCalledWithMessage = null;
       Order testOrder = new Order(“TestValue”);
    
       // Act
       OrderProcesser target = new OrderProcesser();
       target.ProcessOrder(testOrder);
    
       // Assert
       Assert.AreEqual(“Processing Order: TestValue”, 
           this.mockLogger.LogToOperationsCalledWithMessage);
    
    }
    

Home page on MSDN | Community site