Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing for Server.MapPath

I've a method. which retrieve a document from hard disk. I can't test this from unit testing. It always throw an exception invalid null path or something. How to test that. I've temporarily created session for unit test. But I can't for this Server.MapPath. How to do that ?

like image 586
Jeeva J Avatar asked Oct 24 '13 10:10

Jeeva J


2 Answers

If you need to test legacy code which you can't or don't want to change, you can try FakeHttpContext.

This is how it works:

var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "path");
using (new FakeHttpContext())
{
    var mappedPath = Http.Context.Current.Server.MapPath("path");
    Assert.Equal(expectedPath, mappedPath);
}
like image 136
vAD Avatar answered Nov 15 '22 19:11

vAD


You can use dependancy injection and abstraction over Server.MapPath

public interface IPathProvider
{
   string MapPath(string path);
}

And production implementation would be:

public class ServerPathProvider : IPathProvider
{
     public string MapPath(string path)
     {
          return HttpContext.Current.Server.MapPath(path);
     }
}

While testing one:

public class TestPathProvider : IPathProvider
{
    public string MapPath(string path)
    {
        return Path.Combine(@"C:\project\",path);
    }
}
like image 34
Krzysztof Cieslak Avatar answered Nov 15 '22 18:11

Krzysztof Cieslak