Today I wrote some code to output URLs in a certain manner in an ASP.NET MVC project. The code I wrote was extremely simple, but I struggled, I mean S-T-R-U-G-G-L-E-D, to write tests against the new code and ensure correctness. I could easily very visually that it was working but the amount of setup and kludge around ViewContext, RequestContext and ControllerContext was causing me to pull my hair out.
I tweeted my frustrations as I packed up and left work for the day and got the following responses soon thereafter:
@TimBarcz outbound routing is still hard, sadly (from @subdigital)
@TimBarcz …a way to test #aspnetmvc a helper to reduce the ridiculous noise/setup would be helpful (from @ehexter)
Determined to not give up I pulled down the MVCContrib source and started to peck away. I’m working on committing and finalizing the code but here is a sneak peak of the changes. Hopefully you agree that it is an improvement.
Before:
1: [Test]
2: public void Should_correctly_generate_session_url()
3: {
4: new RouteConfigurator().RegisterRoutes();
5: var builder = new TestControllerBuilder();
6: var context = new RequestContext(builder.HttpContext, new RouteData());
7: context.HttpContext.Response.Expect(x => x.ApplyAppPathModifier(null)).IgnoreArguments().Do(new Func<string, string>(s => s)).Repeat.Any();
8: var urlhelper = new UrlHelper(context);
9: string url = urlhelper.RouteUrl("session", new { sessionKey = "this-is-the-session", conferenceKey = "austincodecamp" });
10: url.ShouldEqual("/austincodecamp/sessions/this-is-the-session");
11: }
After:
1: [Test]
2: public void should_be_able_to_generate_url_from_named_route()
3: {
4: OutBoundUrl.OfRouteNamed("session").ShouldMapToUrl("/sessions");
5: }
And
1: [Test]
2: public void should_be_able_to_generate_url_from_controller_action()
3: {
4: OutBoundUrl.Of<FunkyController>(x => x.New()).ShouldMapToUrl("/Funky/New");
5: }
Much, much cleaner and easier on the eyes.
It’s not quite done yet and has some holes (accepting additional route values, etc) but it’s worthy of discussion and once completed should make one very frustrating aspect of testing in MVC even easier.
Posted
08-27-2009 12:15 AM
by
Tim Barcz