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