Test-Driven Development

Test-Driven Development by Example
Test-Driven Development by Example

Test-Driven Development or TDD was introduced in a book written by Kent Beck. In short, TDD is a discipline in software development to write a failed test and then make it pass. Repeat this process until the software fulfills the requirements.

That book or the principle of TDD is old but famous until this day. I believe that most of us have heard that. But many of us didn't implement it very well. TDD is simple, but it is a discipline. Test first, then code. Not the opposite. I saw many software developers didn't implement this discipline even though they knew about it. Some of the reasons:

Unit tests are important. It brings confidence to us while refactoring. Writing unit tests are not time-wasting. It is a must. So, we must prepare time for that. Imagine if you have a bunch of code. It was an old project. Your job is to add a feature there. You are afraid to add it because you think maybe it will make some conflicts with existing features. You asked your friend, QA, to test it manually because you have no automated tests. That was wasting resources because they not only test your features. Maybe they need to test all features.

The book is about 200 pages. I didn't read all pages. But let me try to give some gist of the book here. Feel free to leave me a comment if I missed something.

In TDD, we write new code only if an automated test has failed and eliminate duplication. These two rules imply an order to how we code called Red-Green-Refactor.

  1. Red. Write a failed test, even if the class or method that we called is undefined.
  2. Green. Make the test pass. Code it until pass.
  3. Refactor. Eliminate all duplication or repetition.

Bugs come even we have unit tests. Sometimes that happens when we write code first, then unit tests. Maybe there is some untested code? So, 100% test coverage is a must. Make sure the tests meet the requirements too.

In that book, Kent Beck gave 2 samples to demonstrate TDD with Java; the money example and Fibonacci. Let me give you another one. I demonstrated TDD with TypeScript and Jest. The demonstration is in video format that we can watch on YouTube. I think video is the best format for this. There are also a lot of TDD demonstrations on YouTube but most of them didn't complete the development. That's another reason for me to make another one. I built a simple calculator that does basic calculations such as addition, subtraction, multiplication, and division. It has 100% test coverage.

Related Articles


comments powered by Disqus