gpt4 book ai didi

asp.net-mvc - 如何对 Razor View 进行单元测试

转载 作者:行者123 更新时间:2023-12-04 08:55:03 32 4
gpt4 key购买 nike

当斯科特·格思里first blogged on Razor时,他写道

The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).



但是,我找不到关于 Razor 可测试性的其他陈述(或示例)。
有使用 CodelanguageServie RazorGeneratorsome self-made renderer的指针-我不将其称为“按设计”。

目前是否可以以简单的方式对 Razor View 进行单元测试? (在asp.net mvc应用程序中,即NancyFx在其nancy.testing-package中带来了可测试性。)

(目前我不在乎 if views should be tested or not。)

我知道有 loads of questions like this one,但是大多数都比较老。

最佳答案

我认为您可以对任何Razor View 进行单元测试,如下所示:

ViewResult v = View("~/Views/Home/Index.cshtml");
if (string.IsNullOrEmpty(v.ViewName))
v.ViewName = RouteData.GetRequiredString("action");
ViewEngineResult result = null;
StringBuilder sb = new StringBuilder();
StringWriter textwriter = new StringWriter(sb);
HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
if (v.View == null)
{
result = new ViewEngineResult(new RazorView(ControllerContext,"~/Views/Home/Index.cshtml", null,false,null), new RazorViewEngine());
v.View = result.View;
}
ViewContext viewContext = new ViewContext(ControllerContext, v.View, ViewData, TempData, htmlwriter);
v.View.Render(viewContext, htmlwriter);
string html = sb.ToString();

之后,您可以解析html以检查内容是否符合规范。

关于asp.net-mvc - 如何对 Razor View 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436994/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com