关于MvcContrib TestHelpers的新手问题

Sim*_*max 2 asp.net asp.net-mvc mvccontrib-testhelper

我刚开始在MvcContrib中使用TestHelpers.我想尝试在我的控制器上测试一个动作方法,该方法本身测试IsAjaxRequest()是否为真.

我使用了TestHelper示例中显示的相同代码来设置TestControllerBuilder

_controller = new StarsController();    
_builder = new TestControllerBuilder();
_builder.InitializeController(_controller);
Run Code Online (Sandbox Code Playgroud)

所以_controller里面有所有伪造/模拟的HttpContext,这真的很棒.但是我现在要做什么来强制内部伪造的Request对象上的IsAjaxRequest()返回true?

Sim*_*max 7

这是我使用的代码,我在页​​面顶部的问题中的代码使用MvcContrib testhelpers来创建一个非常伪造的控制器(_controller),内部有伪造版本的HttpRequest,HttpResponse等.然后根据Patrick的建议我创建了一个新的头文件包含X-Requested-With条目的集合.然后告诉_controller.HttpContext.Request.headers在尝试查看标题时返回我的标题集合(即调用IsAjaxRequest()时发生的情况).

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

    _controller.HttpContext.Request.Stub(r => r.Headers).Return(headers);
Run Code Online (Sandbox Code Playgroud)

就像一种享受.