Tdd
What is TDD
Test-driven development
TDD vs Unit Testing
- TDD -> code, code is generated according to the test case
- code -> unit testing, in other words, unit testing based on code, it only test the existed code
- unit testing is part of TDD
Flow
- list all requirements
- for each requirement, write a test case to make it fail
- write enough code to make current test case and all previous test cases pass
- refactor the code, eleminate duplication if necessary
- 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
- TDD is not required at every case, it is unnecessary for easy task.
- Its core are well test cases and building small function as possible as you can
- Steps of TDD are not strict, e.g. empty implementation can be skip