Reputation: 3251
I'm using HttpContext.Current.Server.MapPath()
in my method to fetch document.
To write unit test for this method,
What do I have to do in:
How do I Mock this?
I subjected to do a unit test only for Current.Server.Mappath()
not for Path.Combine()
Upvotes: 2
Views: 5882
Reputation: 124794
Probably the best solution is to avoid using Server.MapPath
: for example, you can replace:
Server.MapPath("~/MyFolder/MyFile.dat")
by:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"MyFolder\MyFile.dat")
Upvotes: 10
Reputation: 3085
This is my suggestion:
In your app:
{...
var destinationPath= IOHelper.MapPath(DatafeedFolderName);
...
}
This is the code of the help method
public static string MapPath(string subFolder)
{
return HttpContext.Current.IsNull()
? Path.Combine(Directory.GetCurrentDirectory(), subFolder)
: HttpContext.Current.Server.MapPath(subFolder);
}
And the unit test can use:
{...
Assert.True(runtime_path, Directory.GetCurrentDirectory() + "\destimationPath"
...}
Upvotes: 0
Reputation: 22822
This is typical with code that calls static methods, it's very difficult to test while preserving separation of concern and avoiding tight coupling. Here is a generic approach to test and mock "untestable code": write a "facade wrapper" to it.
Create a wrapper for these methods. A simple class that contains methods named sensibly, and only delegates to the untestable calls (typically static calls)
Create an interface to that wrapper class
Instead of directly calling the untestable methods in your client code, use the wrapper (dependency-injected using the interface provided in step 2) and call normal methods on it.
In your unit-test, mock the wrapper with the behaviour you want.
This approach effectively reduces the coupling and separates the concerns that need to be separated. Of course, you still can't test the behaviour of the wrapper itself, but if it's simple enough (only delegating to the original calls) then it's not as big a problem.
Upvotes: 4