使用Rhino Mock在c#中模拟静态方法

时间:2012-06-25 09:58:59

标签: c# .net rhino-mocks

在c#中模拟静态类的最佳方法是什么。例如:

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

我想模仿这个,但需要将它包装在一个带接口的类中,最好的方法是什么,这种方法适用于所有静态方法吗?

这种方法会不会产生很多无意义的接口和类?

1 个答案:

答案 0 :(得分:6)

  

在c#

中模拟静态类的最佳方法是什么

最好的方法是隐藏抽象背后的静态调用。那些可以伪造。例如:

public interface IApplicationPhysicalPathProvider
{
    string ApplicationPhysicalPath { get; }
}

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

这个建议适用于任何模拟框架,即使你根本不使用模拟框架。

相关问题