views:

653

answers:

2

We have just started using ASP.Net MVC Release Candidate and the test project we have was previously testing Ajax requests with MVC beta.

The old code looked something like this:

Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();
Mock<HttpContextBase> context = new Mock<HttpContextBase>();

context.Expect(c => c.Request).Returns(request.Object);
context.Expect(c => c.Response).Returns(response.Object);

request.Expect(req => req["__MVCASYNCPOST"]).Returns("true");

MyController controller = new MyController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
ViewResult result = controller.UpdateStatus() as ViewResult;

The call to UpdateStatus would then use the IsMvcAjaxRequest() method on the request object to determine what to return to the browser.

The change in ASP.Net MVC Release Candidate to the Request.IsMvcAjaxRequest() to an extension method of Request.IsAjaxRequest() means that the way we mock the request headers is changed to:

request.Expect(req => req["X-Requested-With"]).Returns("XMLHttpRequest");

I hope others find this useful

+1  A: 

This issue and many others are covered in Scott Guthrie's blog on RC1. Look for the section on AJAX improvements. Another thing that I have noticed is that UpdateModel no longer takes a FormCollection. I'm having to rework my unit tests to mock up the Request.Form NameValueCollection. The resulting code is probably better, though, so the pain is worth it.

EDIT: Another gotcha. If you have an existing MVC application that uses ASP.NET MVC Ajax, you'll need to manually update your Javascript files or it won't recognize the requests as AJAX requests. The old javascript files add the __MVCASYNCPOST form field mechanism instead of setting the X-Requested-With HTTP header. I found the new versions in C:\Program Files\Microsoft ASP.NET\ASP.NET MVC RC\Temp\MvcWebApplicationProjectTemplateRC.cs.zip -- in the Scripts directory.

tvanfosson
+1  A: 

I was aware that Scott Gu's blog mentions the change but it doesn't provide any code examples of the impact on test code or the value that needs to be returned in order to mock an Ajax request. thought this might provide a quick and simple fix for this change in the release candidate.

Scott Littlewood