Posted by: Dennis | August 15, 2010

Avoid mocking for Request.IsAjaxRequest

A small nauseating thing about the Request.IsAjaxRequest is that there is no real nice way to test methods that use it.

The normal approach to test methods that use it is to mock the controllercontext

public void MakeRequestAjax(ControllerBase controller)
{
      var controllerContext = MockRepository.GenerateMock<ControllerContext>();
      controllerContext.Expect(c => c.HttpContext.Request["X-Requested-With"]).Return("XMLHttpRequest");
      controller.ControllerContext = controllerContext;
}

But Seriously, thats like shooting birds with a cannon.

Like shooting birds with a cannon

The much simpler approach is add a small wrapper to your controller  (or your controller baseclass)

private bool? _isAjaxRequest;
internal bool IsAjaxRequest
{
  get { return _isAjaxRequest ?? Request.IsAjaxRequest(); }
  set { _isAjaxRequest = value; }
}

Then in your test code you explicitly set it to true or false. If you don’t set it, then it will use the standard method of looking up the result.

Advertisement

Categories

Follow

Get every new post delivered to your Inbox.