How to Unit Test HtmlHelper with Moq?

前端 未结 4 1722
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  -上瘾入骨i
    2021-02-03 20:47

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

提交回复
热议问题