Newbie question on MvcContrib TestHelpers

两盒软妹~` 提交于 2019-12-12 10:09:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!