Pre-Compiled View Does Not Render Correctly in a Unit Test

Jul 19, 2012 at 5:35 PM

I have a pre-compiled view that has a couple of partial views, and when I try to unit test the view, it doesn't render as HTML correctly.

@model PageViewModel
@section ContentSection
    @if (@Model != null)
        <table id="contentLayout">
                <td class="layoutCellLeft">
                    <div id="Overview">@Html.Partial("_ZonePartial", 
                <td class="layoutCellLeft">@Html.Partial("_ContentTabsPartial")</td>

If I unit test the partial views (_ZonePartial and _ContentTabsPartial), they render correctly.  It seems as though the if block is failing (if @Model != null), as the HTML that I get back is just blank lines (\r\n\r\n\r\n).

Unit Test:

        [Description("Validate the Index view")]
        public void Views_IndexTest()
            var view = new Index();
            SharedController controller = new SharedController();
            ViewResult result = (ViewResult)controller.Index();
            PageViewModel model = (PageViewModel)result.ViewData.Model;
            HtmlDocument document = view.RenderAsHtml(model);
            HtmlNode contentLayoutNode = document.GetElementbyId("contentLayout");
            Assert.IsNotNull(contentLayoutNode, "Cannot find contentLayout element");
Jul 31, 2012 at 12:16 AM

Is it rendering anything in the Content section? Please try to isolate whether the issue is Model related or ContentSection related.

Jul 31, 2012 at 12:30 AM

I found a resource that talks about using view.RenderSection(sectionName) to get the HTML that I needed.  I don't have the link at this time.