views:

64

answers:

2

Hi,

I'm just starting to use the TestHelpers in MvcContrib. I want to try and test an action method on my controller that itself tests if IsAjaxRequest() is true.

I've used the same code that is shown in the TestHelper samples to set up the TestControllerBuilder

_controller = new StarsController();    
_builder = new TestControllerBuilder();
_builder.InitializeController(_controller);

So that _controller has all the faked/mocked HttpContext inside it, which is really great. But what do I do now to force IsAjaxRequest() on the internally faked Request object to return true?

A: 

You need to stub out the HttpRequest.Headers property to return a NameValueCollection that contains an entry for "X-Requested-With" with the value "XMLHttpRequest".

Patrick Steele
Thanks thats sounds good but how do I actually do that. I really don't know Rhino Mocks at all. I've used Moq a little but I wouldn't know where to start with stubbing out the HttpRequest.Headers property. Could you show me a little code to get me started Patrick?
Simon Lomax
Its ok, I figured it out. I've added another answer so I can paste in the code I used in case it helps anybody else. Thanks Patrick you certainly put me on the right track.
Simon Lomax
var request = _builder.HttpContext.Request;request.Stub(r => r.Headers).Return(new NameValueCollection {{"X-Requested-With", "XMLHttpRequest"}});
Patrick Steele
+1  A: 

Here's the code I used, the code in my question at the top of the page uses MvcContrib testhelpers to create a nicely faked controller (_controller) that internally has faked versions of HttpRequest, HttpResponse etc. Then as per Patrick's advice I created a new headers collection containing an entry for X-Requested-With. Then told _controller.HttpContext.Request.headers to return my headers collection whenever it attempts to look at headers (i.e. which is what occurs when IsAjaxRequest() is called).

    var headers = new NameValueCollection();
    headers.Add("X-Requested-With", "XMLHttpRequest");

    _controller.HttpContext.Request.Stub(r => r.Headers).Return(headers);

Works like a treat.

Simon Lomax