Monday, April 20, 2015

Unit test HttpResponseMessage when it is returned from a Web API controller in C#!

using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ApiControllerTesting.Controllers
{
   public class WhateverController : ApiController
   {
      public HttpResponseMessage Post()
      {
         string commentary = "I like cats!";
         return Request.CreateResponse(HttpStatusCode.Created, commentary);
      }
   }
}

 
 

Per this what is above may be tested like so:

using System.Net.Http;
using System.Web.Http;
using ApiControllerTesting.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ApiControllerTesting.Tests.Controllers
{
   [TestClass]
   public class WhateverControllerTest
   {
      [TestMethod]
      public void Test()
      {
         string goody;
         WhateverController whateverController = new WhateverController();
         whateverController.Request = new HttpRequestMessage();
         whateverController.Configuration = new HttpConfiguration();
         HttpResponseMessage httpResponseMessage = whateverController.Post();
         httpResponseMessage.TryGetContentValue<string>(out goody);
         Assert.AreEqual(goody, "I like cats!");
      }
   }
}

 
 

On the controller side, we are, in this example, returning the response in a shape different than I am used to. I am used to handing back strings or serialized objects as strings like so:

return new HttpResponseMessage
{
   Content = new StringContent("I like cats!")
};

 
 

...but, I cannot figure out how to both do this and test it. Rats!

No comments:

Post a Comment