Search code examples
c#.netrhino-mocks

Mocking static methods in c# using Rhino Mock


What is the best approach for mocking out a static class in c#. For instance:

String appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

I want to mock this but will need to wrap it in a class with an interface, what is the best approach and does this approach work for all static methods?

Will this approach not make a lot of allmost pointless interfaces and classes?


Solution

  • What is the best approach for mocking out a static class in c#

    The best approach is to hide those static calls behind abstractions. Those can be faked. For instance:

    public interface IApplicationPhysicalPathProvider
    {
        string ApplicationPhysicalPath { get; }
    }
    
    public class AspNetApplicationPhysicalPathProvider : IApplicationPhysicalPathProvider
    {
        public string ApplicationPhysicalPath 
        {
            get { return HostingEnvironment.ApplicationPhysicalPath; }
        }
    }
    

    This advice holds for any mocking framework and even if you don't use a mocking framework at all.