keskiviikko 11. tammikuuta 2012

TDD or better known as Test Driven Development

In Test Driven Development, the idea is to create test cases before you create the application code itself. Simple as that, or is it? It seems a lot of people don't get the idea behind TDD and instantly ask how can one create test scripts for a code that doesn't exist yet. Let's go over this process and learn the true power and efficiency you obtain with test driven development method.

So you open your favorite IDE (Zend Studio or Eclipse PDT in my case). You know you want to create a user class so you first define functions for it by writing down the specifications of course. You can the class skeleton, and functions to set and get user's last name.

Now you need to write down a test script for the class. But how exactly and what should you test for? Well, have a look at yours specs. You have a User class and according to your specifications, you have getter and setter for the lastname.

<?php
  class myClassTest extends PHPUnit_Framework_TestCase
  {
    public function testClass()
    {
      $user = new User();

      $this->assertEquals('User',get_class($user));
    }
  }

Now you have the very beginning of your test script. It's doesn't test much yet, but it will do for now. Now if you run this test with PHPUnit, you will get an error due to non-existing class file. So what do you do next? Create the class file itself.

<?php 
  class User
  {
  }

Yes, now we have a class file created and when we run the above test script again, we get a success this time. We tested that the instance of $user is class of User.

Getting the point now? First we write the test scripts based on the specifications and then little by little we add to the class and test on each iteration that all of those tested areas are added to the class and passing the objectives defined.

This method, of course, requires great amount of effort put down on writing down the specifications. This, however, should not come as a surprise to anyone dealing with web development.

But do you really want to know the great thing about this method? Haven't figured it out yet? When you get your class completely written and ready, you already have test cases created for that class!

Tell me how many times you really have time to create test scripts after you have written the classes? Even after 12 years of web development career, I have not seen one developer who writes test scripts with great joy and pleasure. If writing down test cases based on specifications and then writing classes to satisfy those test cases would be a way of development, we would be that one step better developers.

Ei kommentteja:

Lähetä kommentti