如何对剃刀视图进行单元测试 [英] How to unit-test a razor-view

查看:50
本文介绍了如何对剃刀视图进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Scott Guthrie 首先在Razor上发帖时,他写道

When Scott Guthrie first blogged on Razor, he wrote

新的视图引擎实现将支持单元测试视图的功能(不需要控制器或Web服务器,并且可以在任何单元测试项目中托管-不需要特殊的应用程序域).

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).

但是,我找不到关于剃刀可测试性的其他陈述(或示例).这里有使用的指针 CodelanguageServie RazorGenerator 一些自制的渲染器-我不称其为按设计".

However, I can find no other statement (or example) regarding razor-testability. There are pointers to using the CodelanguageServie or RazorGenerator or some self-made renderer - non of which I would call "by design".

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

Is it currently possible to unit test a razor view the simple way? (In an asp.net mvc-application, that is. I.e. NancyFx brings testability in it's nancy.testing-package.)

(目前我不在乎是否应该测试视图.)

我知道有类似这样的问题,但是其中大多数都是很老的...

I know there are loads of questions like this one, but most of them are rather old...

推荐答案

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

What I think you can unit test any Razor view like following:

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以检查内容是否符合规范.

After this,you can parse the html to check the content with the specification.

这篇关于如何对剃刀视图进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆