.net mvc2 custom HtmlHelper extension unit testing

Posted by alex on Stack Overflow See other posts from Stack Overflow or by alex
Published on 2010-10-15T21:27:48Z Indexed on 2010/12/23 14:54 UTC
Read the original article Hit count: 213

Filed under:
|
|

My goal is to be able to unit test some custom HtmlHelper extensions - which use RenderPartial internally.

http://ox.no/posts/mocking-htmlhelper-in-asp-net-mvc-2-and-3-using-moq

I've tried using the method above to mock the HtmlHelper. However, I'm running into Null value exceptions. "Parameter name: view"

Anyone have any idea?? Thanks.

Below are the ideas of the code:

    [TestMethod]
    public void TestMethod1()
    {
        var helper = CreateHtmlHelper(new ViewDataDictionary());
        helper.RenderPartial("Test");  // supposingly this line is within a method to be tested
        Assert.AreEqual("test", helper.ViewContext.Writer.ToString());
    }


    public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd)
    {
        Mock<ViewContext> mockViewContext = new Mock<ViewContext>(
            new ControllerContext(
                new Mock<HttpContextBase>().Object,
                new RouteData(),
                new Mock<ControllerBase>().Object),
            new Mock<IView>().Object,
            vd,
            new TempDataDictionary(),
            new StringWriter());
        var mockViewDataContainer = new Mock<IViewDataContainer>();
        mockViewDataContainer.Setup(v => v.ViewData)
            .Returns(vd);
        return new HtmlHelper(mockViewContext.Object,
                                mockViewDataContainer.Object);
    }

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about mvc