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

How do I get fake path for HttpContext.Current.Server.MapPath which is assigned to protected object inside method unit testing?

我是单元测试 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 或需要和使用的地方

class Account {
    protected string accfilepath;

    public Account(IPathProvider pathProvider) {
        accfilepath = pathProvider.MapPath("~/files/");
    }
}

使用您选择的模拟框架或 fake/test class 如果模拟框架不可用,

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