Wednesday, 22 September 2010

Mocking HttpCookieCollection in HttpRequestBase

When unit testing ASP.NET MVC2 projects the issue of injecting HttpContext is quickly encountered.  There seem to be many different ways / recommendations for mocking HttpContextBase to improve the testability of controllers and their actions.  My investigations into that will probably be a separate blog post in the near future but for now I want to cover something that had me stuck for longer than it probably should have.  That is how to mock non abstract/interfaced classes within HttpRequestBase and HttpResponseBase – namely the HttpCookieCollection class.   The code sample below illustrates how it can be used within a mocked instance of HttpRequestBase.  Cookies can be added / modified within the unit test code prior to being passed into the code being tested.   After it’s been called, using a combination of MOQ’s Verify and NUnit’s Assert it is possible to check how many times the collection is accessed (but you have to include the set up calls) and that the relevant cookies have been added / set up.

 

MOQ / NUnit Code Sample
  1. namespace Tests
  2. {
  3.     using System.Web;
  4.     using Moq;
  5.     using NUnit.Framework;
  6.  
  7.     [TestFixture]
  8.     public class HttpRequestBaseTests
  9.     {
  10.         [Test]
  11.         public void Test()
  12.         {
  13.             var request = new Mock<HttpRequestBase>();
  14.             request.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());
  15.             request.Object.Cookies.Add(new HttpCookie("TestCookie", "TestValue"));
  16.             request.Object.Cookies.Add(new HttpCookie("AnotherCookie"));
  17.  
  18.             var instance = request.Object;
  19.             var cookie = instance.Cookies["TestCookie"];
  20.  
  21.             request.Verify(r => r.Cookies, Times.Exactly(3));  // Include the one expected reference, plus two setup calls.
  22.  
  23.             Assert.That(cookie, Is.Not.Null.And.InstanceOf(typeof(HttpCookie)));
  24.             Assert.That(cookie.Name, Is.Not.Null.And.InstanceOf(typeof(string)).And.EqualTo("TestCookie"));
  25.             Assert.That(cookie.Value, Is.Not.Null.And.InstanceOf(typeof(string)).And.EqualTo("TestValue"));
  26.         }
  27.     }
  28. }

No comments:

Post a Comment