C# Unit Testing: Testing a method that uses MapPath

Jeff picture Jeff · Aug 11, 2009 · Viewed 12.5k times · Source

First of all, I am aware that this question is dangerously close to: How to MapPath in a unit test in C#

I'm hoping however, that it has a different solution. My issue follows:

In my code I have an object that needs to be validated. I am creating unit tests for each validation method to make sure it is validating correctly. I am creating mock data and loading it into the object, then validating it. The problem is that within the validation, when an error occurs, an error code is assigned. This error code is used to gather information about the error from an xml file using Server.MapPath. However, when trying to get the xml file, an exception is thrown meaning the file cannot be found.

Since MapPath is in my validation code, and not my unit test, how do I get my unit test to recognize the path? Does this question make sense?

Error Line (In my Validation code NOT my unit test):

XDocument xdoc = XDocument.Load(HttpContext.Current.Server.MapPath("App_Data/ErrorCodes.xml"));

Simplified: The Unit Test calls a method in my program that calls Server.MapPath which then fails.

Answer

Chris Missal picture Chris Missal · Aug 11, 2009

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