Test-driven development (TDD), is an evolutionary approach to software development, in which you write a test before you write just enough production code to fulfill that test. The simple goal of TDD is to write clean code that works. Due to this fact, TDD is a method of designing software, not merely a method of testing it. A significant advantage of TDD is that it enables you to take small steps when writing software, and this makes it far more productive than attempting to code in large steps.
I’ve adopted TDD in several mid-size projects in the past 3-4 years, and I’ve come to realize that it works incredibly well alongside traditional black-box or white-box testing. From my experience with it all, I’ve realized that there are three golden rules of TDD:
1. Don’t build what you can’t test: Imagine building a million-dollar software architecture involving several man-hours, only to realize that it cannot be put in production because it cannot be tested due to technical or infrastructure constraints. Large projects are prone to this quite often. However, smaller projects are no exception either. Let’s say, I have to build a simple printer queue manager. I have access to the API, the programming environment etc., but I don’t have access to a variety of printer hardware to test the utility on. The risk of failure increases in such cases, and there’s hardly any mitigation strategy in place.
2. Write a test before writing the code: The core aspect of TDD revolves around writing a test case for a piece of code before writing that piece of code. In TDD each new feature begins with writing a test. This test must fail since it is written before the feature is implemented. But by focusing on writing only the code necessary to pass the test, designs can be cleaner and clearer. Running such tests gives a rapid confirmation of correct behaviour as the code evolves.
3. Test as you build: TDD constantly repeats the steps of adding test cases that fail (no code written yet), passing them with unit testing (code written), and refactoring (code improved). Receiving the expected test results at each stage reinforces the programmer’s mental model of the code, boosts confidence and increases productivity.
While it is true that more code is required with TDD than without TDD because of the additional unit test code, but the total code implementation time is typically shorter, simple because you only write enough code to pass the test.
Overall, TDD can save considerable amount of time, efforts and money, for any development team.