user2285745
user2285745

Reputation: 31

HttpContext is null when trying to unit test a Controller with webgrid

I am trying to unit test a controller with a webgrid as such

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

I always get this error

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

Here's my Test method

    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);

Here's my CreateMockContext method

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;
        }

I can test other controller just fine. Only controllers with webgrid fail. Please help.

Upvotes: 2

Views: 614

Answers (1)

Sixto Saez
Sixto Saez

Reputation: 12680

Is there a reason you're instantiating WebGrid in the controller? It seems based on this MSDN article that you could move the WebGrid instantiation into the view for the controller and remove that dependency from it's logic. That would certainly make writing the unit test much easier.

Upvotes: 1

Related Questions