Share via


Test readability

I read this excellent post on test readability a few days ago. I like the way he shows how he refactors a test for readability but personally I would have written the example test a little bit differently. First of all I would have added another extension method:

 
   1:      public static void PushOkButtonMultipleTimes(this ILoginView view, int times)   
   2:      {   
   3:          for (int i=0; i<times; i++)
   4:              view.PushOkButton();   
   5:      }

With that extension method my version of the test would have looked like this:

 
   1:      [Test]
   2:      public void only_three_login_attempts_are_allowed()
   3:      {
   4:          presenter = given_a_login_presenter_with_bad_credentials();
   5:   
   6:          view.PushOkButtonMultipleTimes(3);
   7:   
   8:          view.ShouldBeClosed();
   9:      }
  10:      
  11:      public ILoginView given_a_login_view_with_bad_credentials()
  12:      {
  13:          ILoginView view = CreateLoginView("BadUser", "BadPassword");
  14:          ILoginService loginService = CreateLoginService(false);
  15:   
  16:          LoginPresenter presenter = new LoginPresenter(loginService);
  17:          presenter.Initialize(view);
  18:          return view;
  19:      }

I personally prefer to move as much as possible of test setup to separate methods that are called explicitly by the test. The use of the extension method to remove the three times duplicated PushOkButton call is not something I'd always do. I was considering having the for-loop in the test method but I think an in place for-loop is less readable than making the calls three times. The extension method wrapping the for-loop however removes the duplication without decreasing the readability of the test.