How to unit-test a razor-view

2019-04-24 11:39发布

问题:

When Scott Guthrie first blogged on Razor, he wrote

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

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

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

(And currently I don't care if views should be tested or not.)

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

回答1:

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

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