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

梦想的初衷 提交于 2019-12-12 18:18:55

问题


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

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();
    }
}

回答1:


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("~/",""));
    }
}

you can then test the system

[TestClass]
class Test {

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

        Account ac = new Account(fakePathProvider);

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

and not be coupled to HttpContext




回答2:


You can create another constructor that takes a path as parameter. That way you can pass a fake path for unit testing



来源:https://stackoverflow.com/questions/38805765/how-do-i-get-fake-path-for-httpcontext-current-server-mappath-which-is-assigned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!