单元测试Web App时如何模拟应用程序路径

Stu*_*ser 11 c# asp.net asp.net-mvc unit-testing mocking

我正在测试MVC HTML帮助程序中的代码,在尝试获取应用程序路径时会抛出错误:

//appropriate code that uses System.IO.Path to get directory that results in:
string path = "~\\Views\\directory\\subdirectory\\fileName.cshtml";
htmlHelper.Partial(path, model, viewData); //exception thrown here
Run Code Online (Sandbox Code Playgroud)

引发的异常是

System.Web.HttpException:应用程序相对虚拟路径'〜/ Views/directory/subdirectory/fileName.cshtml'不能成为绝对路径,因为应用程序的路径未知.

遵循如何在测试HtmlHelper时解决图像路径问题的建议
我假装(使用Moq):

  • Request.Url 返回一个字符串
  • Request.RawUrl 返回一个字符串
  • Request.ApplicationPath 返回一个字符串
  • Request.ServerVariables 返回null NameValueCollection
  • Response.ApplyAppPathModifier(string virtualPath) 返回一个字符串

还需要什么才能允许此代码在单元测试运行的上下文中运行?
或者
我应该采取什么其他方法来渲染动态构建的字符串上的部分视图?

rav*_*avi 9

作为模拟内置.net类的替代方法,您可以

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

public class PathProvider : IPathProvider
{
    private readonly HttpServerUtilityBase _server;

    public PathProvider(HttpServerUtilityBase server)
    {
        _server = server;
    }

    public string GetAbsolutePath(string path)
    {
        return _server.MapPath(path);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用上面的类来获取绝对路径.

对于For单元测试,您可以模拟并注入可在单元测试环境中工作的IPathProvider实现.

- 更新代码