How to perform a single razor test

When Scott Guthrie first blog about Razor , he wrote

The new implementation of the presentation mechanism will support the ability to present unit test (without requiring a controller or web server and can be placed in any unit test project - no special application domain is required).

However, I cannot find another statement (or example) regarding the razor test. There are pointers to using a CodelanguageServie or RazorGenerator or some home-made renderer - without which I would call "by design".

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

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

I know there are a lot of questions like this , but most of them are pretty old ...

+5
source share
1 answer

I think you can unit test view any Razor as shown below:

 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 that, you can parse the html to check the content with the spec.

0
source

Source: https://habr.com/ru/post/1234867/


All Articles