如何在Fack HttpContext中添加视图模型

时间:2014-06-06 15:56:06

标签: c# asp.net-mvc testing httpcontext

我需要测试自定义的Html辅助方法,例如@Html.CustomLabel@Html.CustomLabelFor(m=>m.UserName)

第一个相对容易。我有:

    public static HtmlHelper Create()
    {
        var vc = new ViewContext {HttpContext = new FakeHttpContext()};
        var html = new HtmlHelper(vc, new FakeViewDataContainer());
        return html;
    }

    private class FakeHttpContext : HttpContextBase
    {
        private readonly Dictionary<object, object> items = new Dictionary<object, object>();

        public override IDictionary Items
        {
            get { return items; }
        }
    }

    private class FakeViewDataContainer : IViewDataContainer
    {
        private ViewDataDictionary viewData = new ViewDataDictionary();
        public ViewDataDictionary ViewData
        {
            get{return viewData;}
            set { viewData = value; }
        }
    }

但如何写第二个呢?我需要在HttpContext中注入一个视图模型来编写测试。

    public static HtmlHelper Create<T>()
    {
        var vc = new ViewContext {HttpContext = new FakeHttpContext()};
        var html = new HtmlHelper(vc, new FakeViewDataContainer());
        return html;
    }

如何在方法T中包含该视图模型Create<T>

1 个答案:

答案 0 :(得分:0)

以下是我定义Create<T>方法的方法。

    public static HtmlHelper<T> Create<T>(T viewModel)
    {
        var vd = new ViewDataDictionary();
        vd.Model = viewModel;
        var vc = new ViewContext {HttpContext = new FakeHttpContext(), ViewData = vd};
        var html = new HtmlHelper<T>(vc, new FakeViewDataContainer());
        return html;
    }

使用它:

var html = HtmlHelperFactory.Create(new LoginInputModel());