How to Unit Test HtmlHelper with Moq?

我只是一个虾纸丫 提交于 2019-12-02 23:26:18

What you can do is this:

HtmlHelper helper = null;
helper.YourHelperMethod();

No need to mock anything. Works brilliant for me.

Thomas

Here's another article that shows you how to achieve the same thing:

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);
}

In MVC5, the ViewContext has an extra constructor parameter for a TextWriter, so Thomas' code no longer works. I added an in-memory TextWriter to get around this problem:

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);
}

To test disposable helper like BeginForm with access to ViewContext.Writer you can use this:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!