views:

68

answers:

1

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.

+2  A: 

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);
eu-ge-ne
I still get the exception. Please, see my edited question
eKek0