如何使用Moq对HtmlHelper进行单元测试?

时间:2010-03-22 21:31:48

标签: asp.net-mvc unit-testing nunit moq html-helper

有人可以告诉我如何使用Moq创建模拟HTML Helper吗?

这个article有一篇文章的链接,声称要描述这个,但是在链接之后只返回一个ASP.NET运行时错误

[编辑] 我问了一个与同一主题相关的更具体的问题here,但它没有得到任何答复。我认为它太具体了,所以我想我可以得到一个更一般的问题的更一般的答案,并修改它以满足我的要求。

由于

4 个答案:

答案 0 :(得分:45)

Here的另一篇文章向您展示了如何实现同样的目标:

public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd)
{
  var mockViewContext = new Mock<ViewContext>(
    new ControllerContext(
      new Mock<HttpContextBase>().Object,
      new RouteData(),
      new Mock<ControllerBase>().Object),
    new Mock<IView>().Object,
    vd,
    new TempDataDictionary());

  var mockViewDataContainer = new Mock<IViewDataContainer>();
  mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);

  return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);
}

答案 1 :(得分:19)

在MVC5中,ViewContextTextWriter的额外构造函数参数,因此Thomas的代码不再有效。我添加了一个内存中的TextWriter来解决这个问题:

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 StreamWriter(new MemoryStream())
    );

    Mock<IViewDataContainer> mockDataContainer = new Mock<IViewDataContainer>();
    mockDataContainer.Setup(c => c.ViewData).Returns(vd);

    return new HtmlHelper(mockViewContext.Object, mockDataContainer.Object);
}

答案 2 :(得分:13)

你可以做的是:

HtmlHelper helper = null;
helper.YourHelperMethod();

无需嘲笑任何东西。对我来说很棒。

答案 3 :(得分:1)

要测试像BeginForm这样的一次性助手,可以访问ViewContext.Writer,你可以使用它:

public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd, Stream stream = null)
{
    TextWriter textWriter = new StreamWriter(stream ?? new MemoryStream());
    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(),
        textWriter
    );
    mockViewContext.Setup(vc => vc.Writer).Returns(textWriter);

    Mock<IViewDataContainer> mockDataContainer = new Mock<IViewDataContainer>();
    mockDataContainer.Setup(c => c.ViewData).Returns(vd);

    return new HtmlHelper(mockViewContext.Object, mockDataContainer.Object);
}