Tdd

What is TDD

Test-driven development

TDD vs Unit Testing

  1. TDD -> code, code is generated according to the test case
  2. code -> unit testing, in other words, unit testing based on code, it only test the existed code
  3. unit testing is part of TDD

Flow

  1. list all requirements
  2. for each requirement, write a test case to make it fail
  3. write enough code to make current test case and all previous test cases pass
  4. refactor the code, eleminate duplication if necessary
  5. repeat step 2 to 4

Why

| pros | cons | |————|———-| |only the functions that is needed is written| someone may think it wast time| |reduce the bugs|test cases need to be maintained| |drive and improve the design of the code since we design first then implementation| |easy to check when something go wrong as one test case correspond to some code|

How

step 1

Take calculator for example, its functionality is:

  • add two numbers
  • subtract two numbers
  • multiply two numbers
  • divide two numbers

step 2

Create a Calculator class

public Class Calculator {

}

write a test case like

int expectedResult = Calculator.add(1,2);
assertEqual(expectedResult, 3);

above code has error because there is no add method in Calculator. Hence we need to add this method which looks like(make this test failed, so let it return 0) :

public int add(int param1, int param2) {
    return 0;
}

Then run this case, it failed.

step 3

only add necessary code to make this test success

public int add(int param1, int param2) {
    return param1 + param2;
 }

subtract function is followed, we need to ensure all add test cases and subtract test cases passed.

Conclusion

  1. TDD is not required at every case, it is unnecessary for easy task.
  2. Its core are well test cases and building small function as possible as you can
  3. Steps of TDD are not strict, e.g. empty implementation can be skip
Written on April 13, 2017