I have some code that uses HostingEnvironment.MapPath
which I would like to unit test.
How can I setup HostingEnvironment
so that it returns a path and not null
in my unit test (mstest) project?
I have some code that uses HostingEnvironment.MapPath
which I would like to unit test.
How can I setup HostingEnvironment
so that it returns a path and not null
in my unit test (mstest) project?
Well I was writing a test today for code that I don't control and they used
so here is a C# reflection hack to set that value
Just use this code..
Make a new folder name Reference in root directory and added your file inside this folder.
Use this
Why would you have a code that depends on HostingEnvironment.MapPath in an ASP.NET MVC application where you have access to objects like HttpServerUtilityBase which allow you to achieve this and which can be easily mocked and unit tested?
Let's take an example: a controller action which uses the abstract Server class that we want to unit test:
Now, there are many ways to unit test this controller action. Personally I like using the MVcContrib.TestHelper.
But let's see how we can do this using a mocking framework out-of-the-box. I use Rhino Mocks for this example:
It will depend on what mocking or isolation framework you are using. You might want to look into either a) creating a wrapper type around the static property that can be mocked, or b) using a framework which can mock static properties - e.g. Moles or Typemock Isolator