Test-driven development (TDD) is an iterative agile development technique that emphasizes test-first development, which implies that you write a test before you write production-ready code to make the test pass. The TDD technique focuses on writing clean and quality code by ensuring that the code passes the earlier written tests by continuously refactoring the code.
TDD, being a test-first development approach, places greater emphasis on building well-tested software applications. This allows developers to write code in relation to solving the tasks defined in the tests after a thorough thought process. It is a common practice in TDD that the development process begins with writing the tests code before the actual application code is written.
TDD introduces an entirely new development paradigm and shifts your mindset to begin thinking about testing your code right before you even start writing the code. This contrasts with the traditional development technique of deferring code testing to the later stage of the development cycle, an approach known as test last development (TLD).
TDD has been discussed at several conferences and hackathons. Many technology advocates and bloggers have blogged about TDD, its principles, and its benefits. At the same time, there have been many talks and articles written against TDD. The honest truth is TDD rocks, it works, and it offers great benefits when practiced correctly and consistently.
You might probably be wondering, like every developer new to TDD, why write a test first, since you trust your coding instinct to write clean code that always works and usually will test the entire code when you've done coding. Your coding instinct may be right or it may not. There is no way to validate this assumption until the code is validated against a set of written test cases and passes; trust is good, but control is better.
Test cases in TDD are prepared with the aid of user stories or use cases of the software application being developed. The code is then written and refactored iteratively until the tests pass. For example, a method written to validate the length of a credit card might contain test cases to validate the correct length, incorrect length, and even when the null or empty credit card is passed as a parameter to the method.
Many variants of TDD have been proposed ever since it was originally popularized. A variant is behavior-driven development (BDD) or acceptance test–driven development (ATDD), which follows all the principles of TDD while the tests are based on expected user-specified behavior.