Test Driven Development (TDD) also called as test-first approach by many, is a development approach where we first write tests based on our requirements before writing actual production code.
TDD makes sure that all the intended features of the program are working as expected. Kent Beck, who is credited with having developed or “rediscovered” the technique, stated in 2003 that TDD encourages simple designs and inspires confidence. (source = Wikipedia)
A Test-Driven Development (TDD) cycle usually may have following steps:
- Write a test
- Each new feature begins with writing a test that defines a function or improvements of a function. It makes the developer focus on the requirements before writing the code.
- Run all tests and see if the new test fails
- This validates that the test harness is working correctly.
- Shows that the required behaviour did not already exist.
- Rules out the possibility that the new test is flawed and will always pass.
- The new test should fail for the expected reason.
- Write the actual code
- Write code that causes the test to pass. The new code written at this stage is not perfect and may, for example, pass the test in an inelegant way. That is acceptable because it will be improved and honed later.
- Run tests
- If all test cases now pass, the programmer can be confident that the new code meets the test requirements, and does not break or degrade any existing features. If they do not, the new code must be adjusted until they do.
- Refactor code
- The growing code base must be cleaned up regularly during TDD.
- New code can be moved from where it was convenient for passing a test to where it more logically belongs.
- Duplication must be removed. It also applies to the removal of any duplication introduced to pass the test in previous steps.
- Object, class, module, variable and method names should clearly represent their current purpose and use, as extra functionality is added.
- By continually re-running the test cases throughout each refactoring phase, we can be confident that process is not altering any existing functionality.
- Starting with another new test, the cycle is then repeated to push forward the functionality. The size of the steps should always be small.
- Book: Test Driven Development By Example by Kent Beck.