3

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.

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.