2014-06-06 34 views
0

我需要測試像@Html.CustomLabel@Html.CustomLabelFor(m=>m.UserName)這樣的自定義Html輔助方法。如何在Fack中添加視圖模型HttpContext

第一個比較容易。我有:

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>

回答

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()); 
相關問題