Unit testing for Server.MapPath

后端 未结 3 1754
暖寄归人
暖寄归人 2020-12-01 13:31

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

相关标签:
3条回答
  • 2020-12-01 13:40

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-01 13:43

    I was using NSubstitute and I implemented it as below:

     var fakeContext = Substitute.For<HttpContextBase>();
    fakeContext.Server.MapPath(Arg.Any<string>()).ReturnsForAnyArgs("/set-path/");
    
    0 讨论(0)
  • 2020-12-01 14:00

    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);
    }
    
    0 讨论(0)
提交回复
热议问题