我有一个方法.从硬盘检索文档.我不能通过单元测试来测试这个.它总是抛出异常无效的空路径或其他东西.如何测试.我暂时创建了单元测试会话.但我不能为这个Server.MapPath.怎么做 ?
Krz*_*lak 35
You can use dependancy injection and abstraction over Server.MapPath
public interface IPathProvider
{
string MapPath(string path);
}
Run Code Online (Sandbox Code Playgroud)
And production implementation would be:
public class ServerPathProvider : IPathProvider
{
public string MapPath(string path)
{
return HttpContext.Current.Server.MapPath(path);
}
}
Run Code Online (Sandbox Code Playgroud)
While testing one:
public class TestPathProvider : IPathProvider
{
public string MapPath(string path)
{
return Path.Combine(@"C:\project\",path);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要测试您不能或不想更改的遗留代码,可以尝试FakeHttpContext.
这是它的工作原理:
var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "path");
using (new FakeHttpContext())
{
var mappedPath = Http.Context.Current.Server.MapPath("path");
Assert.Equal(expectedPath, mappedPath);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10637 次 |
| 最近记录: |