C# 如何获取分配给方法单元测试中受保护对象的HttpContext.Current.Server.MapPath的假路径?

C# 如何获取分配给方法单元测试中受保护对象的HttpContext.Current.Server.MapPath的假路径?,c#,asp.net,unit-testing,mstest,C#,Asp.net,Unit Testing,Mstest,我不熟悉单元测试,MSTest。我得到NullReferenceException 如何设置进行单元测试的HttpContext.Current.Server.MapPath class Account { protected string accfilepath; public Account(){ accfilepath=HttpContext.Current.Server.MapPath("~/files/"); } } class Test {

我不熟悉单元测试,MSTest。我得到
NullReferenceException

如何设置进行单元测试的
HttpContext.Current.Server.MapPath

class Account
{
    protected string accfilepath;

    public Account(){
        accfilepath=HttpContext.Current.Server.MapPath("~/files/");
    }
}

class Test
{
    [TestMethod]
    public void TestMethod()
    {
        Account ac= new Account();
    }
}

您可以创建另一个以路径为参数的构造函数。这样,您就可以为单元测试传递一个假路径

HttpContext.Server.MapPath
将需要一个在单元测试期间不存在的底层虚拟目录提供程序。抽象服务背后的路径映射,您可以对其进行模拟以使代码可测试

public interface IPathProvider {
    string MapPath(string path);
}
在具体服务的生产实现中,您可以调用映射路径并检索文件

public class ServerPathProvider: IPathProvider {
    public MapPath(string path) {
        return HttpContext.Current.Server.MapPath(path);
    }
}
您可以将抽象注入到依赖类中,或者在需要和使用的地方

class Account {
    protected string accfilepath;

    public Account(IPathProvider pathProvider) {
        accfilepath = pathProvider.MapPath("~/files/");
    }
}
如果模拟框架不可用,则使用您选择的模拟框架或伪/测试类

public class FakePathProvider : IPathProvider {
    public string MapPath(string path) {
        return Path.Combine(@"C:\testproject\",path.Replace("~/",""));
    }
}
然后可以测试系统

[TestClass]
class Test {

    [TestMethod]
    public void TestMethod() {
        // Arrange
        IPathProvider fakePathProvider = new FakePathProvider();

        Account ac = new Account(fakePathProvider);

        // Act
        // ...other test code
    }
}

不要与HttpContext连接,也许这篇文章会有所帮助