当试图用webgrid对控制器进行单元测试时,HttpContext为空

本文关键字:单元测试 为空 HttpContext 控制器 webgrid | 更新日期: 2023-09-27 18:09:17

我正试图用webgrid对控制器进行单元测试

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

我总是得到这个错误

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

这是我的Test方法

    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的控制器才会失败。请帮助。

当试图用webgrid对控制器进行单元测试时,HttpContext为空

您在控制器中实例化WebGrid的原因是什么?根据这篇MSDN文章,您似乎可以将WebGrid实例化移动到控制器的视图中,并从其逻辑中删除该依赖项。这当然会使编写单元测试更容易。