For the vast majority of us, unit tests are short bits of throw-away code that we write to make sure our programs "worked". We will painstakingly write our classes and methods and then we concoct some ad hoc code to test them. Typically this would involve some kind of simple driver program that would allow us to manually interact with the program we had written.
What is TDD
TDD is a software development approach in which we don't write test cases to see if our code works, but write code to see if our test cases work. We basically write the test case first before writing the code.
There are three laws to TDD:
You may not write production code until you have written a failing unit test.
You may not write more of a unit test than it is sufficient to fail, and not compiling is failing.
You may not write more production code than is sufficient to pass the currently failing test.
These three laws lock you into a cycle that is perhaps thirty seconds long. The tests and the production code are written together, with the tests just a few seconds ahead of the production code.
TDD Vs. Traditional Testing
TDD approach is primarily a specification technique. It ensures that your source code is thoroughly tested at the confirmatory level.
- With traditional testing, a successful test finds one or more defects. It is same as TDD. When a test fails, you have made progress because you know that you need to resolve the problem.
- TDD ensures that your system actually meets requirements defined for it. It helps to build your confidence about your system.
- In TDD more focus is on production code that verifies whether testing will work properly. In traditional testing, more focus is on test case design. Whether the test will show the proper/improper execution of the application in order to fulfill requirements.
- In TDD, you achieve 100% coverage test. Every single line of code is tested, unlike traditional testing.
- The combination of both traditional testing and TDD leads to the importance of testing the system rather than perfection of the system. In Agile Modeling (AM), you should "test with a purpose". You should know why you are testing something and what level its need to be tested.