March 16, 2010

Declarative Style is My Golden Hammer

I was working on a little pet project recently, and I really was tickled when I wrote my unit tests like this:

  public class Given_a_HomeController
  {

    private static HomeController controller;

    [TestClass]
    public class when_asked_for_the_index
    {

      private ActionResult the_result;

      [TestInitialize]
      public void because()
      {
        using_a_new_home_controller();
        after_performing_the_index_action();
      }
      
      public void using_a_new_home_controller()
      {
        controller = new HomeController();
      }

      public void after_performing_the_index_action()
      {
        the_result = controller.Index();
        Assert.IsNotNull(the_result);
      }

      [TestMethod]
      public void it_should_return_a_ViewResult_for_the_Index_view()
      {
        the_result.is_a_ViewResult().for_a_view_named("Index");
      }

    }

If you can read through the test attribute decorators and the public void C# noise, the setup and the tests read like this:

Given a HomeController:
    When asked for the index:
        because:
            using a new HomeController
            after executing the Index action

        it should return a ViewResult for the Index View

It made me smile.

No comments:

Post a Comment