加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 尝试使用Moq模拟HtmlHelper时抛出MissingMethodE

发布时间:2020-12-16 09:32:24 所属栏目:asp.Net 来源:网络整理
导读:当试图遵循 article on mocking the htmlhelper with Moq时,我遇到了以下问题.创建htmlhelper时会抛出异常.我只是猜测正在使用城堡windsor(通过查看错误消息). 例外: MissingMethodException occurred Constructor on type ‘Castle.Proxies.ViewContextPro
当试图遵循 article on mocking the htmlhelper with Moq时,我遇到了以下问题.创建htmlhelper时会抛出异常.我只是猜测正在使用城堡windsor(通过查看错误消息).

例外:

MissingMethodException occurred

Constructor on type ‘Castle.Proxies.ViewContextProxy’ not found.

堆栈跟踪:

at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr,Binder binder,Object[] args,CultureInfo culture,Object[] activationAttributes)

代码:

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

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

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

我正在使用ASP MVC 2,Moq 4.0 beta 3,VS2010,使用IDE的测试框架.

如何解决问题并返回HtmlHelper的实例?

解决方法

我已经通过我的博客文章中的代码重现了您的问题.以下更新的方法适用于我:

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

    mockViewContext.Setup(vc => vc.ViewData).Returns(vd);

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

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

我也发布了一个update on my blog.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读