title: Unit testing HttpResponseMessage with Autofac and Moq
body: <p>I'm going round in circles. So my WebApi returns the output it needs to the browser when i am running in debug. Firefox and IE display the List i need. However when i am trying to unit test the response using Mock and Autofac the <code>HttpResponseMessage</code> I am getting back has no Contents. I get the feeling it is returning on a different context or something like that. I am not totally sure, hence asking the question. I have stringed the below unit test together via googling and the Autofac documentation. </p>
  
  <p>WebApiMethod (contained within <code>InScrapController</code>, <code>_WebScrapSprocService</code> is injected by Autofac in the constructor)</p>
  
  <pre><code>public HttpResponseMessage GetFormItemsByFormNumber(int FormNumber)
  {
      HttpResponseMessage response;
      try
      {
          //response = Request.CreateResponse(HttpStatusCode.OK, _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber),new MediaTypeHeaderValue("application/json"));
          response = Request.CreateResponse(HttpStatusCode.OK, new MediaTypeHeaderValue("application/json"));
          response.Content = new StringContent(JsonConvert.SerializeObject(_WebScrapSprocService.GetFormItemsByFormNumber(FormNumber)),Encoding.UTF8, "application/json");
      } catch (Exception e)
      {
          response = Request.CreateResponse(HttpStatusCode.InternalServerError, new StringContent(e.Message), new MediaTypeHeaderValue("application/json"));
      }
      //Checking if bob knows anything about this...
      string bob = response.Content.ReadAsStringAsync().Result;
      return response;
  }
  </code></pre>
  
  <p>Unit Test</p>
  
  <pre><code>public void GetFormItemsByFormNumber()
  {
      using (var mock = AutoMock.GetLoose())
      {
  
          var Service = mock.Mock&lt;IWebScrapSprocService&gt;().Setup(x =&gt; x.GetFormItemsByFormNumber(3392));
          var service = mock.Create&lt;InScrapController&gt;();
          service.Request = new HttpRequestMessage();
          service.Request.SetConfiguration(new HttpConfiguration());
          var HttpResponse = service.Request.CreateResponse(HttpStatusCode.OK, Service, new MediaTypeHeaderValue("application/json"));
          var response = service.GetFormItemsByFormNumber(3392);
          mock.Mock&lt;IWebScrapSprocService&gt;().Verify(x =&gt; x.GetFormItemsByFormNumber(3392));
          Assert.AreEqual(HttpResponse, response);
      }
  }
  </code></pre>