asp.net-mvc – 如何对剃刀视图进行单元测试

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何对剃刀视图进行单元测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当斯科特格思里 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).

但是,我找不到关于剃刀可测试性的其他声明(或示例).
有指向使用CodelanguageServieRazorGeneratorsome self-made renderer – 非我称之为“按设计”.

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

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

我知道有loads of questions like this one,但大多数都相当古老……

解决方法

我认为您可以对任何Razor视图进行单元测试,如下所示:
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以检查具有规范的内容.

原文链接:https://www.f2er.com/aspnet/247237.html

猜你在找的asp.Net相关文章