[英]Unit testing for Server.MapPath
我有办法 从硬盘上检索文档。 我无法从单元测试中对此进行测试。 它总是抛出一个异常无效的空路径或其他东西。 如何测试。 我已经临时创建了单元测试会话。 但是我不能使用此Server.MapPath。 怎么做 ?
您可以在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);
}
}
如果您需要测试无法更改或不想更改的旧代码,则可以尝试FakeHttpContext 。
它是这样工作的:
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "path");
using (new FakeHttpContext())
{
var mappedPath = Http.Context.Current.Server.MapPath("path");
Assert.Equal(expectedPath, mappedPath);
}
我正在使用NSubstitute,并按以下方式实现了它:
var fakeContext = Substitute.For<HttpContextBase>();
fakeContext.Server.MapPath(Arg.Any<string>()).ReturnsForAnyArgs("/set-path/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.