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 setup calls) and that the relevant cookies have been added/set up.
namespace Tests { using System.Web; using Moq; using NUnit.Framework; [TestFixture] public class HttpRequestBaseTests { [Test] public void Test() { var request = new Mock<HttpRequestBase>(); request.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection()); request.Object.Cookies.Add(new HttpCookie("TestCookie", "TestValue")); request.Object.Cookies.Add(new HttpCookie("AnotherCookie")); var instance = request.Object; var cookie = instance.Cookies["TestCookie"]; request.Verify(r => r.Cookies, Times.Exactly(3)); // Include the one expected reference, plus two setup calls. Assert.That(cookie, Is.Not.Null.And.InstanceOf(typeof(HttpCookie))); Assert.That(cookie.Name, Is.Not.Null.And.InstanceOf(typeof(string)).And.EqualTo("TestCookie")); Assert.That(cookie.Value, Is.Not.Null.And.InstanceOf(typeof(string)).And.EqualTo("TestValue")); } } }
Today I realised that I’d forgotten how spoilt I am using Resharper and dotCover to run my unit tests. Put another way I’d forgotten how badly Visual Studio plays with any other unit test frameworks other than MS Test! I’m used to and really like the fluent API style of NUnit’s Assert.That(…) syntax so having to fall back to MS Test always feels like a step back. If you ever find yourself in a situation . . .
When I first started looking into Windows Workflow one of the first things that I liked about it was how it separated responsibilities. The workflow was responsible for handling the procedural logic with all its conditional statements, etc. Whilst individual code activities could be written to handle the business logic processing; created in small easily re-usable components. To try and realise my original perception this series of blog posts will cover the unit testing of . . .