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的控制器失败。 请帮忙。
我在做服务器端分页,需要传递一个_db.Count()作为rowCount,我不想通过ViewBag传递它。 – user2285745
我对'WebGrid'不熟悉,但更好的方法可能是使用[强类型视图](http://www.asp.net/mvc/tutorials/views/dynamic-v-strongly-typed-视图)来传递计数。在我看来,管理网格元素属于视图而不是管理员责任。这样,控制器仍然专注于与模型交互并将适当的数据传递给视图。只是我的2位:) –
我在这里有同样的问题,但在我的情况下,我实例化ViewModel中的WebGrid。能够单元测试我的模型的那部分,但看起来不可能是很好的。 – rushinge