Tutorial :How to test an ajax submition in ASP.NET MVC?


Specifically, how can I pass the static method Request.IsAjaxRequest()?

I get the exception 'System.ArgumentNullException' when I try to test the following code:

if (Request.IsAjaxRequest())  {    return Json(data);  }  return View(data2);  

I'm using Moq. Thanks for any help.


You need mocking Request and Request.Headers to work with Request.IsAjaxRequest():

var request = new Mock<HttpRequestBase>();  request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {      {"X-Requested-With", "XMLHttpRequest"}  });    var context = new Mock<HttpContextBase>();  context.SetupGet(x => x.Request).Returns(request.Object);    var controller = new YourController();  controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »