I'm using HostingEnvironment.MapPath() on my webapplication get the path of the location to save the file. I used MockHost for populate fake values in Unit testing. When running on visual studio or IIS it works fine. But when running unit test HostingEnvironment.MapPath() fails when that map path does not have a file. But it works fine if that location has a file. Could some one tell me how to run unit test successfully HostingEnvironment.MapPath() without a file reside in MapPath location.
///Code///
public static Tuple<string, string GetFilePathForSave(SampleVWModel model, int uploadId)
{
if (model == null)
{
return null;
}
ConfigurationDto configurationDto = new ConfigurationDto();
configurationDto = facade.RetrieveConfiguration();
var fileName = string.Format("[{0}]-{1}", uploadId.ToString(),Path.GetFileName(model.Uplodedfile.FileName));
var path=HostingEnvironment.MapPath(configurationDto.UploadFolderPath + fileName);
var tuple = new Tuple<string, string>(fileName, path);
return tuple;
}
///UnitTest Code///
[TestMethod()]
public void GetFilePathForSaveTest()
{
string path = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.FullName + "\\MainApplication";
MockHost host = new MockHost(path, "/");
host.Setup();
SampleVWModel vwModel= new SampleVWModel ();
vwModel.FilePath = path + @"\App_Data\Uploads\excelDoc.xlsx";
var uploadedFile = new Mock<HttpPostedFileBase>();
uploadedFile.Setup(x => x.ContentLength).Returns(30);
uploadedFile.Setup(x => x.ContentType).Returns("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
uploadedFile.Setup(x => x.FileName).Returns("excelDoc.xlsx");
vwModel.Uplodedfile = uploadedFile.Object;
Tuple<string, string> result = Helper.GetFilePathForSave(vwModel, 1014);
Assert.AreEqual("[1014]-excelDoc.xlsx", result.Item1);
}
As in the code UploadFile will save after getting the path from GetFilePathForSave is normal behavior. But when doing the unit testing HostingEnvironment.MapPath() is failing because mappath does not have the file.