Server.MapPath的单元测试

问题描述 投票:10回答:3

我有一种方法。从硬盘上检索文档。我无法从单元测试中对此进行测试。它总是抛出一个异常无效的空路径或其他东西。如何测试。我已经临时创建了单元测试会话。但是我不能使用此Server.MapPath。怎么做?

c# unit-testing
3个回答
35
投票

您可以在Server.MapPath上使用依赖注入和抽象

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

并且生产实现为:

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

同时测试一个:

public class TestPathProvider : IPathProvider
{
    public string MapPath(string path)
    {
        return Path.Combine(@"C:\project\",path);
    }
}

9
投票

如果您需要测试无法更改或不想更改的旧代码,可以尝试FakeHttpContext

这是它的工作方式:

var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "path");
using (new FakeHttpContext())
{
    var mappedPath = Http.Context.Current.Server.MapPath("path");
    Assert.Equal(expectedPath, mappedPath);
}

0
投票

我正在使用NSubstitute,并按如下所示实施了它:]

 var fakeContext = Substitute.For<HttpContextBase>();
fakeContext.Server.MapPath(Arg.Any<string>()).ReturnsForAnyArgs("/set-path/");
© www.soinside.com 2019 - 2024. All rights reserved.