Я пытаюсь модульного тестирования контроллера с 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 бита :) –
У меня такая же проблема, но в моем случае я создаю WebGrid в моей ViewModel. Было бы неплохо иметь возможность тестировать часть моей модели, но похоже, что это невозможно. – rushinge