8

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);
    }
1
  • You'll need to post more details so we can reproduce the problem. I've used the aforementioned code (I wrote it) for testing controllers that render views with RenderPartial without problems. Commented Oct 18, 2010 at 20:39

2 Answers 2

3

Check this out...its a great article http://blogs.teamb.com/craigstuntz/2010/09/10/38638/

Sign up to request clarification or add additional context in comments.

1 Comment

I was able to use this article to easily unit test my HtmlHelper extension in MVC 3. Good stuff!
2

I was facing the same issue. When I pass the arguments to new Mock(), it is not setting them correctly. You need to set them up explicitly:

mockViewContext.Setup(v => v.View).Returns(new Mock<IView>().Object);
mockViewContext.Setup(v => v.ViewData).Returns(viewData);
mockViewContext.Setup(v => v.TempData).Returns(new TempDataDictionary());
mockViewContext.Setup(v => v.Writer).Returns(writer);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.