Server.MapPath的unit testing

我有一个方法。 从硬盘检索文档。 我无法通过unit testing来测试这个。 它总是抛出exception无效的空路径或其他东西。 如何测试。 我暂时创建了unit testing会话。 但我不能为这个Server.MapPath。 怎么做 ?

您可以在Server.MapPath上使用dependency injection和抽象

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); } } 

如果您需要测试您不能或不想更改的遗留代码,可以尝试FakeHttpContext 。

这是它的工作原理:

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