本文介绍了如何获取方法单元测试中分配给受保护对象的HttpContext.Current.Server.MapPath的伪路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是单元测试的新手,MSTest.我得到NullReferenceException.

I am new to unit test, MSTest. I get NullReferenceException.

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

How do I set HttpContext.Current.Server.MapPath for doing unit test?

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将需要基础虚拟目录提供程序,该虚拟目录提供程序在单元测试期间不存在.在可以模拟以使代码可测试的服务后面抽象路径映射.

HttpContext.Server.MapPath would require an underlying virtual directory provider which would not exist during the unit test. Abstract the path mapping behind a service that you can mock to make the code testable.

public interface IPathProvider {
    string MapPath(string path);
}

在具体服务的生产实现中,您可以调用以映射路径并检索文件.

In the production implementation of the concrete service you can make your call to map the path and retrieve the file.

public class ServerPathProvider: IPathProvider {
    public MapPath(string path) {
        return HttpContext.Current.Server.MapPath(path);
    }
}

您将把抽象注入到您的依赖类中或需要和使用的地方

you would inject the abstraction into your dependent class or where needed and used

class Account {
    protected string accfilepath;

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

如果没有可用的模拟框架,请使用您选择的模拟框架或伪造/测试类,

Using your mocking framework of choice or a fake/test class if a mocking framework is not available,

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

这篇关于如何获取方法单元测试中分配给受保护对象的HttpContext.Current.Server.MapPath的伪路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:11