.net mvc2自定义HtmlHelper扩展单元测试

ale*_*lex 8 asp.net-mvc unit-testing html-helper

我的目标是能够对一些自定义HtmlHelper扩展进行单元测试 - 这些扩展在内部使用RenderPartial.

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

我尝试使用上面的方法来模拟HtmlHelper.但是,我遇到了Null值异常."参数名称:视图"

任何人都有任何想法?谢谢.

以下是代码的想法:

    [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);
    }
Run Code Online (Sandbox Code Playgroud)

Joh*_*ock 3

看看这个......这是一篇很棒的文章 http://blogs.teamb.com/craigstuntz/2010/09/10/38638/