Unit test views that have Layout specified with RazorGenerator

Jan 26, 2012 at 11:03 PM

I am trying to unit test a view and validate HTML that is rendered that has a Layout specified, but nothing gets rendered.  If I remove layout it works fine.  Here is a sample of my view.  What I want to validate is the HTML in the LeftPane.

    Layout = "~/Views/Shared/_TwoPaneLayout.cshtml";

@section StyleSheet

    <link href="@Url.Content("~/Content/css/smb-error.css?" + @Model.BuildNumber)" rel="stylesheet" type="text/css" />

@section LeftPane


Here is my unit test code.

            var view = new Portal.Views.Shared.Error();
            ErrorModel model = new ErrorModel();
            model.Exception = new Exception("Unit test");
            // unknown error
            model.Type = ErrorModel.ErrorType.Unknown;
            HtmlDocument doc = view.RenderAsHtml<ErrorModel>(model);
For this my HtmlDocument comes back with just a couple of \r\n and no Html.
Jan 27, 2012 at 12:07 AM

I think the problem is that the unit test logic only ends up rendering the top level markup, and ignores the named sections.

It does raise the question of how exactly this should work. The general unit testing assumption is that we only want to render the one page itself, but not any other associated pages. When there are multiple sections, I guess they could be rendered sequentially, maybe with some header/separator.

Jan 27, 2012 at 8:13 PM

So it sounds like there is not a way to unit test views that utilize a master page since the sections are not rendered.  Are there any plans for including this capability?  It works great for my partial views, but would like to be able to validate HTML output for my views that utilize master page as part of my unit tests.

Jan 27, 2012 at 10:35 PM

You should open a bug to track the scenario, as it had not come up before. And of course, contributions are welcome! :)

Feb 1, 2012 at 4:53 PM

I found a solution.  If I first call RenderAsHtml and pass in the model and then call RenderSection I can check the output of the section.

            HtmlDocument doc = view.RenderAsHtml<ErrorModel>(model);
            string html = view.RenderSection("LeftPane").ToHtmlString();