2013-04-16 46 views
2

一個控制器我試圖單元測試控制器具有的WebGrid這樣HttpContext的努力單元時,測試用的WebGrid

var grid = new WebGrid(ajaxUpdateContainerId: "container-grid",ajaxUpdateCallback: "setArrows", canSort: true); 

我總是得到這個錯誤

System.ArgumentNullException: Value cannot be null. 
Parameter name: httpContext 

這裏是我的測試是空方法

var mockContext = CreateMockContext(); 
    UserController target = new UserController(); 
    target.ControllerContext = new ControllerContext(); 
    target.ControllerContext.HttpContext = mockContext.Http.Object; 
    Nullable<int> page = new Nullable<int>(); 
    string sort = "CreatedDate"; 
    string sortdir = "ASC"; 
    ActionResult actual; 
    actual = target.Payments(page, sort, sortdir); 
    Assert.IsNotNull(actual); 

這裏是我的CreateMockContext方法

public UnitTestBase CreateMockContext() 
     { 
      this.RoutingRequestContext = new Mock<RequestContext>(MockBehavior.Loose); 
      this.ActionExecuting = new Mock<ActionExecutingContext>(MockBehavior.Loose); 
      this.Http = new Mock<HttpContextBase>(MockBehavior.Loose); 
      this.Server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose); 
      this.Response = new Mock<HttpResponseBase>(MockBehavior.Loose); 
      this.Request = new Mock<HttpRequestBase>(MockBehavior.Loose); 
      this.Session = new Mock<HttpSessionStateBase>(MockBehavior.Loose); 
      this.Cookies = new HttpCookieCollection(); 

      this.RoutingRequestContext.SetupGet(c => c.HttpContext).Returns(this.Http.Object); 
      this.ActionExecuting.SetupGet(c => c.HttpContext).Returns(this.Http.Object); 
      this.Http.SetupGet(c => c.Request).Returns(this.Request.Object); 
      this.Http.SetupGet(c => c.Response).Returns(this.Response.Object); 
      this.Http.SetupGet(c => c.Server).Returns(this.Server.Object); 
      this.Http.SetupGet(c => c.Session).Returns(this.Session.Object); 
      this.Http.SetupGet(p => p.User.Identity.Name).Returns("admin"); 
      this.Http.SetupGet(p => p.Request.IsAuthenticated).Returns(true); 
      this.Request.Setup(c => c.Cookies).Returns(Cookies); 
      return this; 
     } 

我可以測試其他控制器就好了。只有帶有webgrid的控制器失敗。 請幫忙。

回答

1

是否有你在控制器中實例化WebGrid的原因?它似乎基於this MSDN article,您可以將WebGrid實例化到控制器的視圖中,並從其邏輯中移除該依賴關係。這肯定會使編寫單元測試變得更容易。

+0

我在做服務器端分頁,需要傳遞一個_db.Count()作爲rowCount,我不想通過ViewBag傳遞它。 – user2285745

+0

我對'WebGrid'不熟悉,但更好的方法可能是使用[強類型視圖](http://www.asp.net/mvc/tutorials/views/dynamic-v-strongly-typed-視圖)來傳遞計數。在我看來,管理網格元素屬於視圖而不是管理員責任。這樣,控制器仍然專注於與模型交互並將適當的數據傳遞給視圖。只是我的2位:) –

+0

我在這裏有同樣的問題,但在我的情況下,我實例化ViewModel中的WebGrid。能夠單元測試我的模型的那部分,但看起來不可能是很好的。 – rushinge