jueves, 9 de junio de 2011

Test Driven Development - TDD

Let's talk about Test Driven Development. Surely, many people knows about it nevertheless when they try to apply it, they realise that they must spend many time to change mind of developpers and this will raise that development time grow up. And that's true, this is because in this post, I will try to expose some practices and examples to help about how to use TDD.


TDD may be viewed like a philosophy where developer must calm down him/herself before to start programming.

First, we need to answer some questions when we want to create a new class:

- What will this class be able to perform?

"- I want to create a very simple utility calculator with sum, substract, divide and multiplication operations."

Secondly, you must imagine how you would like to use your class.

"-I would like to use this class, specifying by parameters the operators for the operations."

Third, type the unit tests that you thought in the previous step. To remark, these unit tests will fail because operators are still not implemented.

"
public void Sum_WhenTwoParameters_ThenResultIsCorrect {

    Int32 x = 10;
 Int32 y = 20;
 Int32 result = 30;

 Int32 resReturned = Calculator.Sum(x, y);

 Assert.IsEqual(resReturned, result);
}

...
"


Fourth, implement the operators in order to pass all your unit tests:

"
public static class Calculator {
 public static int Sum(int? x, int? y) {

  int result = x;

  for(int index = 0; index < y; index ++) {
   result++;
  }

  return result;
 }

...
}

"

Fifth, refactor your code taking into consideration passing all your unit tests.

"
public static class Calculator {
 public static int Sum(int? x, int? y) {
  return x + y;
 }

...
}

"

Sixth, add new functionality (new operators...) and start again. If you start implementing the easier functionality and, step by step, you add new functionality following these rules. You will have a usefull code, with a high code coverage and fully-tested.

No hay comentarios:

Publicar un comentario