title: How to mock the Request on Controller in ASP.Net MVC?
body: <p>I have a controller in C# using the ASP.Net MVC framework</p>
  
  <pre><code>public class HomeController:Controller{
    public ActionResult Index()
      {
        if (Request.IsAjaxRequest())
          { 
            //do some ajaxy stuff
          }
        return View("Index");
      }
  }
  </code></pre>
  
  <p>I got some tips on mocking and was hoping to test the code with the following and RhinoMocks</p>
  
  <pre><code>var mocks = new MockRepository();
  var mockedhttpContext = mocks.DynamicMock&lt;HttpContextBase&gt;();
  var mockedHttpRequest = mocks.DynamicMock&lt;HttpRequestBase&gt;();
  SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);
  
  var controller = new HomeController();
  controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
  var result = controller.Index() as ViewResult;
  Assert.AreEqual("About", result.ViewName);
  </code></pre>
  
  <p>However I keep getting this error:</p>
  
  <blockquote>
    <p>Exception
      System.ArgumentNullException:
    System.ArgumentNullException : Value
    cannot be null.   Parameter name:
    request   at
    System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(HttpRequestBase
    request)</p>
  </blockquote>
  
  <p>Since the <code>Request</code> object on the controller has no setter. I tried to get this test working properly by using recommended code from an answer below.</p>
  
  <p>This used Moq instead of RhinoMocks, and in using Moq I use the following for the same test:</p>
  
  <pre><code>var request = new Mock&lt;HttpRequestBase&gt;();
  // Not working - IsAjaxRequest() is static extension method and cannot be mocked
  // request.Setup(x =&gt; x.IsAjaxRequest()).Returns(true /* or false */);
  // use this
  request.SetupGet(x =&gt; x.Headers["X-Requested-With"]).Returns("XMLHttpRequest");
  
  var context = new Mock&lt;HttpContextBase&gt;();
  context.SetupGet(x =&gt; x.Request).Returns(request.Object);
  var controller = new HomeController(Repository, LoginInfoProvider);
  controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
  var result = controller.Index() as ViewResult;
  Assert.AreEqual("About", result.ViewName);
  </code></pre>
  
  <p>but get the following error:</p>
  
  <blockquote>
    <p>Exception     System.ArgumentException:
    System.ArgumentException : Invalid
    setup on a non-overridable member:    x
    => x.Headers["X-Requested-With"]  at Moq.Mock.ThrowIfCantOverride(Expression
    setup, MethodInfo methodInfo)</p>
  </blockquote>
  
  <p>Again, it seems like I cannot set the request header.
  How do I set this value, in RhinoMocks or Moq?</p>