问题
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?
回答1:
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".
回答2:
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.
来源:https://stackoverflow.com/questions/2929058/newbie-question-on-mvccontrib-testhelpers