Unit test views that have Layout specified with RazorGenerator

Jan 27, 2012 at 12:03 AM

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
{
 
    <h1>@PortalStrings.Global_Error</h1>
    <h3>@Model.Header</h3>
    <h6>@Html.Raw(Model.Message)</h6>

...

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.
Coordinator
Jan 27, 2012 at 1: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 9: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.

Coordinator
Jan 27, 2012 at 11: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 5: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();