I'm trying to write unit tests for actions that contains checks for Request.IsAjaxRequest().
I've gone by the example given here[1] for mocking properties on the HttpContext object using Moq:
But it fails with "Invalid expectation on a non-overridable member" (I guess since it's a static method).
Because IsAjaxRequest is extension method, you cannot set it up in moq, but you can just make sure it acts how you want, by setting properties it looks for on HttpRequestBase. Current implementation of IsAjaxRequest looks for key "X-Requested-With" in request
or request headers with value "XMLHttpRequest".
bjartekv
Member
13 Points
5 Posts
Unit testing actions with IsAjaxRequest
Jan 29, 2009 07:41 AM|LINK
I'm trying to write unit tests for actions that contains checks for Request.IsAjaxRequest().
I've gone by the example given here[1] for mocking properties on the HttpContext object using Moq:
But it fails with "Invalid expectation on a non-overridable member" (I guess since it's a static method).
Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
controllerContext.Expect(r => r.HttpContext.Request.IsAjaxRequest()).Returns(false);
controller.ControllerContext = controllerContext.Object;
Anyone know of a way to test for this? I ended up splitting the ajax part into a different action instead.
regards,
Bjarte
[1] http://weblogs.asp.net/scottgu/archive/2009/01/27/asp-net-mvc-1-0-release-candidate-now-available.aspx
molesinski
Member
314 Points
71 Posts
Re: Unit testing actions with IsAjaxRequest
Jan 29, 2009 11:08 AM|LINK
Hey,
Because IsAjaxRequest is extension method, you cannot set it up in moq, but you can just make sure it acts how you want, by setting properties it looks for on HttpRequestBase. Current implementation of IsAjaxRequest looks for key "X-Requested-With" in request or request headers with value "XMLHttpRequest".
Mock controllerContext = new Mock();
controllerContext.Expect(r => r.HttpContext.Request["X-Requested-With"]).Returns("XMLHttpRequest");
controller.ControllerContext = controllerContext.Object;
Now controller.ControllerContext.HttpContext.Request.IsAjaxRequest() will return true.
ps. I cannot check if this code is valid right now, but I am pretty sure even if its not, then you can adjust it for your needs.
bjartekv
Member
13 Points
5 Posts
Re: Unit testing actions with IsAjaxRequest
Jan 29, 2009 11:39 AM|LINK
Hey,
Ah thanks, that works! I was wondering which property to set.
Regards,
Bjarte