C# Unit Testing: Testing a method that uses MapPath

丶灬走出姿态 提交于 2019-12-03 04:55:20

I would abstract out the "filename provider" into an class that simply returns a location, then you can mock it much, much easier.

public class PathProvider
{
    public virtual string GetPath()
    {
        return HttpContext.Current.Server.MapPath("App_Data/ErrorCodes.xml");
    }
}

Then, you can either use the PathProvider class directly...

PathProvider pathProvider = new PathProvider();
XDocument xdoc = XDocument.Load(pathProvider.GetPath());

Or mock it out in your tests:

PathProvider pathProvider = new MockPathProvider(); // using a mocking framework
XDocument xdoc = XDocument.Load(pathProvider.GetPath());

After some rigorous googling and some help from a colleague we came up with a simple solution already built into .net

Above the unit tests that accesses the validation process, I added:

 [TestMethod()]
 [HostType("ASP.NET")]
 [UrlToTest("http://localhost:###/upload_file.aspx")]
 [AspNetDevelopmentServerHost("Path To Web Application", "Path To Web Root")]

This works perfectly. Basically, when the test is called, it loads the URL with the specified unit test in the page load. Since it is a web site that is now calling the unit test, the validation will have access to Server.MapPath. This solution may not work for everyone, but it was perfect for this. Thanks to all you contributed.

Lewis

Try using Rhino Mocks or an alternative mocking framework to Mock the httpContext (or other dependent objects) Or you could write your own mock objects. Or write a MapPathWrapper class, inherit from a MapPathWrapperBase class for your real environment, then in for your unit tests create a MockMapPathWrapper object.

There should be plenty of examples for mocking on SO.

Here's one I asked:

How to use Rhino Mocks to Mock an HttpContext.Application

UPDATE I only have experience doing this with the Asp.Net MVC, with webforms I imagein it would be a lot more difficult because of the lack of an HttpContextBase class.

I would extract methods that accept your dependencies as arguments:

public void Validate(HttpContext context)
{
    ValidatePath(context.Server.MapPath("App_Data/ErrorCodes.xml"));
}

public void ValidatePath(string path)
{
    XDocument xdoc = XDocument.Load(path);
    ValidateDocument(xdoc);
}

public void ValidateDocument(XDocument xdoc)
{
    // Original code
}

You can then test the various methods independently. For example, testing how ValidatePath() handles a missing file.

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