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

Jul 19, 2012 at 6: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">
            <tr>
                <td class="layoutCellLeft">
                    <div id="Overview">@Html.Partial("_ZonePartial", 
                        @Model.Content.Zones[ZoneNameKey.Overview])
                    </div>
                </td>
            </tr>
            <tr>
                <td class="layoutCellLeft">@Html.Partial("_ContentTabsPartial")</td>
            </tr>
        </table>
    }
 
}

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:

        [TestMethod]
        [TestCategory("Views")]
        [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;
 
            this.AddContentTabs(model);
 
            HtmlDocument document = view.RenderAsHtml(model);
 
            HtmlNode contentLayoutNode = document.GetElementbyId("contentLayout");
 
            Assert.IsNotNull(contentLayoutNode, "Cannot find contentLayout element");
        }
Coordinator
Jul 31, 2012 at 1: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 1: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.