如何获取HttpContext.Current.Server.MapPath的伪路径,该路径分配给方法unit testing中的受保护对象?

我是unit testing的新手,MSTest。 我得到NullReferenceException

如何设置HttpContext.Current.Server.MapPath进行unit testing?

 class Account { protected string accfilepath; public Account(){ accfilepath=HttpContext.Current.Server.MapPath("~/files/"); } } class Test { [TestMethod] public void TestMethod() { Account ac= new Account(); } } 

HttpContext.Server.MapPath将需要一个底层虚拟目录提供程序,它在unit testing期间不存在。 摘要可以模拟的服务背后的路径映射,以使代码可测试。

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

在具体服务的生产实现中,您可以调用映射路径并检索文件。

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

你会将抽象注入你的依赖类或需要和使用的地方

 class Account { protected string accfilepath; public Account(IPathProvider pathProvider) { accfilepath = pathProvider.MapPath("~/files/"); } } 

如果没有模拟框架,可以使用您选择的模拟框架或假/测试类,

 public class FakePathProvider : IPathProvider { public string MapPath(string path) { return Path.Combine(@"C:\testproject\",path.Replace("~/","")); } } 

然后你可以测试系统

 [TestClass] class Test { [TestMethod] public void TestMethod() { // Arrange IPathProvider fakePathProvider = new FakePathProvider(); Account ac = new Account(fakePathProvider); // Act // ...other test code } } 

而不是耦合到HttpContext

您可以创建另一个将路径作为参数的构造函数。 这样你就可以通过一个假的路径进行unit testing