如何模拟应用路径时

如何模拟应用路径时

本文介绍了如何模拟应用路径时,单元测试Web应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC HTML辅助抛出试图获取应用程序的路径时,错误的测试code:

I am testing code in a MVC HTML helper that throws an error when trying to get the application path:

//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

时引发的例外是

System.Web.HttpException:该应用相对虚拟路径〜/查看/目录/子目录/ fileName.cshtml'不能进行绝对的,因为对应用程序的路径是未知的

继How测试时使用的图像路径​​来解决问题的HtmlHelper?结果
我曾伪造(使用MOQ):

Following the advice of How to resolve issue with image path when testing HtmlHelper?
I have faked (using Moq):


  • Request.Url 返回一个字符串

  • Request.RawUrl 返回一个字符串

  • Request.ApplicationPath 返回一个字符串

  • Request.ServerVariables 来返回一个空的NameValueCollection

  • Response.ApplyAppPathModifier(字符串virtualPath)返回一个字符串

  • Request.Url to return a string
  • Request.RawUrl to return a string
  • Request.ApplicationPath to return a string
  • Request.ServerVariables to return a null NameValueCollection
  • Response.ApplyAppPathModifier(string virtualPath) to return a string

还有什么是需要能够让这个code在单元测试运行的上下文中运行?结果
或结果
我应该采取什么另一种方法来呈现一个动态生成的字符串的局部视图?

What else is needed to be able to allow this code to run in the context of a unit test run?
Or
What other approach should I be taking to render a Partial view on a dynamically built string?

推荐答案

作为一种替代嘲讽内置.NET类,你可以

As an alternative to mocking built-in .net classes, you can

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

使用上述类来获得绝对路径。

Use the above class to get absolute paths.

并为单元测试,你可以模拟并注入IPathProvider的实现,将在单元测试环境下工作。

And for For unit testing you can mock and inject an implementation of IPathProvider that would work in the unit testing environment.

- 更新code

--UPDATED CODE

这篇关于如何模拟应用路径时,单元测试Web应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 18:02