在 MVC3 中测试自定义 Razor 助手
我根据此处的说明创建了一个自定义助手<一href="http://ttp://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx" rel ="nofollow noreferrer">这里。下面是它的一个片段 (ThemeHelper.cs)
:
@inherits Helpers.HelperPage
@using System.Web.Mvc
@using System.Web.Mvc.Html
@...
@helper PathTo(string fileName) {
@Url.Content("~/Content/Themes/" + Theme.CurrentTheme.FolderName + "/" + fileName);
}
我已按照说明将其放置在 App_Code 中。我可以在我的视图中使用这些助手,这就是我想要的。
现在我的问题是,我该如何测试这个东西?例如,我无法通过反射方式获取 ThemeHelper
类的实例,无论是在当前程序集中,还是通过反射方式访问 App_Code
或 __Code
程序集(两者实际上都没有返回)。
理想情况下,我想以某种方式调用这些函数并验证结果/HTML。我有一个框架(HtmlUnit 2.7 的 C# 版本),允许我请求 URL 并验证 HTML。
有没有办法测试我的自定义助手?我想写一些类似的东西:
ThemeHelper h = new ThemeHelper(); // or: Assembly.CreateInstance(...) or something
string html = h.PathTo("Site.css");
Assert.IsTrue(html.contains("Themes");
I've created a custom helper according to instructions here and here. Here's a snippet of what it looks like (ThemeHelper.cs)
:
@inherits Helpers.HelperPage
@using System.Web.Mvc
@using System.Web.Mvc.Html
@...
@helper PathTo(string fileName) {
@Url.Content("~/Content/Themes/" + Theme.CurrentTheme.FolderName + "/" + fileName);
}
I've placed this in App_Code, as instructed. I can use these helpers in my views, which is what I want.
Now my question is, how do I test this thing? I cannot, for example, reflectively get an instance of the ThemeHelper
class, neither in the current assembly nor by reflectively accessing the App_Code
or __Code
assemblies (neither of which actually return).
Ideally, I would like to somehow call these functions and verify the results/HTML. I have a framework in place (C# version of HtmlUnit 2.7) that allows me to request URLs and verify the HTML.
Is there a way to test my custom helper? I would like to write something like:
ThemeHelper h = new ThemeHelper(); // or: Assembly.CreateInstance(...) or something
string html = h.PathTo("Site.css");
Assert.IsTrue(html.contains("Themes");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
单独测试 Razor Page 帮助程序并不容易。
为了具有可单元测试和与视图无关的帮助程序(不依赖于您使用的特定视图引擎),您应该使用标准 HTML 帮助程序,这些帮助程序作为
HtmlHelper
或UrlHelper< /代码> 类。例子:
It won't be easy to unit test Razor Page helpers in isolation.
In order to have unit testable and view agnostic helpers (not dependent on the specific view engine you are using) you should use standard HTML Helpers that come as an extension method to the
HtmlHelper
orUrlHelper
classes. Example: