0

I have to unittest one method that uses appSettings to get filename, that is later used inside HostingEnvironment.MapPath.

BLL method to test contains the following line where _appSettings.SampleName return some filename in Web project. Later filePath is used to open given file.

string filePath = HostingEnvironment.MapPath(_appSettings.SampleName);     
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    ...

In UnitTesting project I have the following structure:

<UnitTestProject.Test>\Resources\MyFile.xlsx

In my unittest I was able to mock _appSettings (_appSettings: IAppSettings) and I can set _appSettings.SampleName any value I wish. This value is really taken inside method I am testing. However, I tried to set _appSettings.SampleName to "Resources\MyFile.xlsx" as well as other values like @"....\Resources\MyFile.xlsx".

However, I always get filePath = null.

Someone marked that htis is duplicate: Unit Testing: DateTime.Now, but I do not need to Mock this method. I have already mocked appsettings, but I am not able to understand why HostingEnvironment.MapPath doesn't work as I want. I am mocking appsettings returing path I wish, but HostingEnvironmentm.MapPath doesn't work. THus probably I do not understand how HostingEnvironment works.

Community
  • 1
  • 1
renathy
  • 5,125
  • 20
  • 85
  • 149
  • You have not understood my question, I am not asking how to unittest static method, I know how to mock it, but I cannot mock it with desired value. Always when I mock it wish new value, I cannot get it to go to desired folder. Morover, I have to write unitttest, I am not able to change existing code. – renathy Apr 24 '16 at 16:35
  • 1
    @AlexeiLevenkov I am sorry, I do not understand how example with DateTime helps me in my case. – renathy Apr 24 '16 at 16:38
  • Probably behaves like that because there is no hosting environment when running the tests. You need to mock this out. – Lasse V. Karlsen Apr 24 '16 at 16:56
  • Reopened. Since you already know all ways to mock static method it sounds like you need good explanation of MapPath... Consider checking out source code -I don't think there are many people familiar with such details. Most would go with changing code or some heavy weight framework like moles (whatever it is currently called) – Alexei Levenkov Apr 24 '16 at 17:32

0 Answers0