title: How can I mock the Response.StatusCode with Moq?
body: <p>I have the following method:</p>
  
  <pre><code>    public void SetHttpStatusCode(HttpStatusCode httpStatusCode)
      {
          Response.StatusCode = (int)httpStatusCode;
      }
  </code></pre>
  
  <p>And the following test:</p>
  
  <pre><code>    [TestMethod]
      public void SetHttpStatusCode_SetsCorrectStatusCode()
      {
          //Arrange
          //Any url will suffice
          var mockHttpContext = TestHelpers.MakeHttpContext(""); 
          mockHttpContext.SetupSet(x =&gt; x.Response.StatusCode = It.IsAny&lt;int&gt;());
  
          //creates an instance of an asp.net mvc controller
          var controller = new AppController()
          {
           ControllerContext = new ControllerContext() { 
                     HttpContext = mockHttpContext.Object }
                               };
  
          // Act
          controller.SetHttpStatusCode(HttpStatusCode.OK);
  
          //Assert
          mockHttpContext.VerifySet(x =&gt; x.Response.StatusCode = It.IsAny&lt;int&gt;());
      }
  </code></pre>
  
  <p>Also, Here is MakeHttpContext</p>
  
  <pre><code> public static Mock&lt;HttpContextBase&gt; MakeHttpContext(string url)
      {
          var mockHttpContext = new Mock&lt;HttpContextBase&gt;();
          var mockRequest = new Mock&lt;HttpRequestBase&gt;();
          var mockResponse = new Mock&lt;HttpResponseBase&gt;();
          var mockSession = new Mock&lt;HttpSessionStateBase&gt;();
  
          //request
          mockRequest.Setup(x =&gt; x.AppRelativeCurrentExecutionFilePath).Returns(url);
          mockHttpContext.Setup(x =&gt; x.Request).Returns(mockRequest.Object);
  
          //response
          mockResponse.Setup(x =&gt; x.ApplyAppPathModifier(It.IsAny&lt;string&gt;())).Returns&lt;string&gt;(x =&gt; x);
          mockHttpContext.Setup(x =&gt; x.Response).Returns(mockResponse.Object);
  
          //session
          mockHttpContext.Setup(x =&gt; x.Session).Returns(mockSession.Object);
  
          return mockHttpContext;
      }
  </code></pre>
  
  <p>When I run the test, I get the following exception:</p>
  
  <pre><code>    Test method PA.Tests.Controllers.AppControllerTest.SetHttpStatusCode_SetsCorrectStatusCode
  threw exception: 
  
  
        Moq.MockException: 
          Expected invocation on the mock at least once, 
          but was never performed: x =&gt; x.StatusCode = It.IsAny&lt;Int32&gt;()
  
          Configured setups:
          x =&gt; x.StatusCode = It.IsAny&lt;Int32&gt;(), Times.Never
          No invocations performed.
  </code></pre>
  
  <p>How does Moq expect/require invocations to be called? I've debugged the SetHTTPStatusCode method, the response object is indeed a mocked object, however Moq insists that there was no invocation. Am I missing something? </p>
  
  <p>Thanks!</p>