How to Unit Test HtmlHelper with Moq?

前端 未结 4 1731
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 20:06

Could somebody show me how you would go about creating a mock HTML Helper with Moq?

This article has a link to an article claiming to describe this, but following the li

4条回答
  •  再見小時候
    2021-02-03 20:58

    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 mockViewContext = new Mock(
            new ControllerContext(
                new Mock().Object,
                new RouteData(),
                new Mock().Object
            ),
            new Mock().Object,
            vd,
            new TempDataDictionary(),
            new StreamWriter(new MemoryStream())
        );
    
        Mock mockDataContainer = new Mock();
        mockDataContainer.Setup(c => c.ViewData).Returns(vd);
    
        return new HtmlHelper(mockViewContext.Object, mockDataContainer.Object);
    }
    

提交回复
热议问题