Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test a razor-view

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

like image 515
Nils Avatar asked Oct 30 '15 13:10

Nils


People also ask

What is unit test frontend?

Unit testing It analyzes individual components and functions to ensure they're working as expected. This is crucial for any frontend application, testing your components and features against how you expect them to behave in production, leading to a stable codebase and a reliable app for your customers.

What is razor view in asp net core?

Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.

How small should a unit test be?

There is no concrete rule for the size of a unit test obviously, but there are some heuristics people use when writing unit tests. A couple of them are that a unit test shouldn't exceed a dozen or so lines and a unit test shouldn't take more than a minute to write. Unit tests are supposed to be as short as possible.


1 Answers

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.

like image 163
Raheem Khan Dawar Avatar answered Oct 21 '22 21:10

Raheem Khan Dawar