Server.MapPath
would require an underlying virtual directory provider which would not exist during the unit test. Abstract the file content retrieval behind a service that you can mock to make the code testable.
public interface IPathProvider {
string MapPath(string path);
}
In the 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);
}
}
In unit test you can mock the service to return what ever data you want for the test.
Here is an example with Moq
//Arrange
var path = "~/resources/file.xml";
var expected = "My/Hard/Coded/File/Path/File.xml";
public mock = new Mock<IPathMapper>();
mock.Setup(m => m.MapPath(path)).Returns(expected);
IPathMapper mapper = mock.Object.
IMyFIleLoader loader = new MyFIleLoader(mapper);
//Act
var actual = loader.Load(path);
//Assert
mock.Verify(m => m.MapPath(path));
//...other code removed for brevity
And here is an example using a fake/test class
public class TestPathProvider : IPathProvider {
public string MapPath(string path) {
return Path.Combine(@"C:\project\",path);
}
}
Reference Unit testing for Server.MapPath