vendredi 20 janvier 2012

Getting started with TDD - Test Driven Development

Update: Here is the GitHub repository containing a FlashBuilder project containing the final test:
Flex-HashMap

I am just familiar with some basic concepts of unit testing. I didn't have the chance to work in a professional environment that would allow me to write unit tests for complicated business code, so all I've tried is really simple examples like the famous addition example. In this article, I'm trying to get a little bit more in depth by using TDD (Test Driven Development).
Test Driven Development can be defined as reversing the traditional development life-cycle upside down. Instead of writing the tests after our code is ready to be tested, the first thing we do is to write tests even before we have any code to test. The code is written for the sole purpose of making tests pass. So the development life-cycle is as follows:
- add a test
- make sure that the test fails
- write the simplest code to make the test pass
- refractor
- do it again
as simple as that. The benefits for using TDD come from the fact that we are repeating very short development life-cycles, and as a result we end up having a high quality and error prone code. I'm implementing the unit tests for a HashMap class implemented in AS3 By Eric J. Feminella. You can find the final code here :
Eric J. Feminella HashMap Implementation. Though, I will be making some changes to it later, I'll put the final code on github.
Of course, in TDD, we have to begin by writing the tests, so before implementing that class, we need to implement a test class:

package tn.zuro.tests.collections
{
    public class HashMapTest
    {        
        private var map:IMap;

        [Before]
        public function setUp():void
        {
            map = new HashMap();
        }
        [After]
        public function tearDown():void
        {
        }
    }
}

Here is our first failing test. A test that doesn't compile can be considered as a failing test. Our test won't compile here since the compiler won't recognize neither IMap or HashMap as we have not implemented them yet. Now let's write some code to make this test pass or at least compile.

package tn.zuro.collections
{
    public interface IMap
    {
    }
}

package tn.zuro.collections
{
    public interface HashMap
    {
    }
}
Now our code will compile, but it still fails: we haven't implemented any runnable methods yet. Let's start by adding some basic methods. The HashMap in our case will use flash.utils.Dictionary since it allows us to implement key/value pairs. we could start by implementing a test method for the method put:
[Test]
public function testPut():void
{
    map.put("d", "value A");
    map.put("e", "value B");
    map.put("f", "value C");
    map.put("u", "value X");
    map.put("v", "value Y");
    map.put("w", "value Z");
}
Now if we run the test, it will fail, the method is not implemented. We go back to IMap, and we add the put method declaration:
function put(key:*, value:*) : void;

Now we need to implement the simplest possible code to make the test pass:
public function put(key:*, value:*) : void
{
    _map[key] = value;
}
Finally, we have a test that passes without problems. Our first iteration is complete, now we have to repeat. We will test the size method next, so that we can add some assertions to our code:
[Test]
public function testSize():void
{
    assertEquals(map.size(), 6);
    map.put("d", "value D");
    assertEquals(map.size(), 7);
    map.put("a", "value K");
    assertEquals(map.size(), 7);
}
We can also add some code to the setUp method, so that we have some key/value pairs in our hashmap to play with.
private var map:IMap;
[Before]
public function setUp():void
{
    map = new HashMap();
    map.put("a", "value A");
    map.put("b", "value B");
    map.put("c", "value C");
    map.put("x", "value X");
    map.put("y", "value Y");
    map.put("z", "value Z");
}
The test fails again, since the method size doesn't exist, yet. Thus, we declare it in the interface and implement it in the HashMap class:
function size() : int;
        
public function size() : int
{
    var length:int = 0;
    for ( var key:* in _map )
    {
        length++;
    }
    return length;
}
The loop
for (var key:* in _map)
allows us to iterate over the keys of the dictionary, to iterate over the values, we can use a for each loop. Now our test passes again, and we can see the results of our assertions. In the method testSize, we have the following assertions:
assertEquals(map.size(), 6);
which should return true since we have put 6 values in the setUp method. We are also sure that the put method works the way it should be.
assertEquals(map.size(), 7);
returns true for the same reasons
and then:
    map.put("a", "value K");
    assertEquals(map.size(), 7);
    this returns true as well, because we used the same key again, so we have
_map["a"] = "value K";
which updates the value associated with the key "a".
   
Let's repeat one more time to make sure we got the process right, and to understand how useful tests can be.
I'm going to add a test for the clear method which will remove all the elements from the dictionary. The clear method will use another method which will remove a key/value pair from the dictionary. We should start by adding a testRemove method to have a failing test, make the test pass, and repeat again. We skipped the refractoring step here, cause the code is too simple and does not require any refractoring. Then we repeat again. Then we write a test for the clear method.
[Test]
public function testRemove():void
{
    map.remove("a");
    assertEquals(map.size(), 5);
}
        
[Test]
public function testClear():void
{
    map.clear();
    assertEquals(map.size(), 0);
}
IMap.as
function remove(key:*) : void;
function clear() : void;
HashMap.as
public function remove(key:*) : void
{
    _map[ key ] = undefined;
    delete _map[ key ];
}
        
public function clear() : void
{
    for ( var key:* in _map )
    {
        remove( key );
    }
}
Now that all the code of the two iterations is in place, everything should be working smoothly, right? Well, not quite. The test method testClear is going to fail. This means that there is a problem with the clear function. The problem comes from the first instruction in the remove function. 
_map[key] = undefined;
I managed to find the problem after I asked a question in StackOverflow: Flex dictionary question. If we didn't test this code thouroghly, it's possible we wouldn't notice this error. And using TDD, we noticed it very early in the development lifecycle, so that it could be corrected very early, and now we have less bugs to worry about. The remove function should look like this:
public function remove(key:*) : void
{
    delete _map[ key ];
}
And this time, the tests pass. I guess that's all what's TDD is about. It's not complicated. It just takes a little time to get used to it, and once we know it good enough, it can speed up development significantly.

Aucun commentaire:

Enregistrer un commentaire