Introduction to Test-Driven Development
Learn about Test-Driven Development in an intuitive way
Test-Driven Development or TDD is a paradigm in which the tests drive the development of software. Let's learn what TDD is and why it's useful.
How is software developed usually?
- Requirements are received. It could be requirements for a new feature or a bug report.
- The requirements are understood by the developer and code changes are done.
- Tests are written for the code changes.
As can be noticed the tests are written in step 3, so this is not a paradigm in which the tests drive the development of software. If we imagine the development process as a vehicle in motion 🚌, the tests are the passenger. In many cases this passenger might be forgotten and not even present in the vehicle. 😀
Let's say that the tests are not forgotten and they are written after
the code changes are done. Can we identify a problem with this
paradigm in which the test are written after the code changes have
been done?
The problem is that the code changes influence the tests. The tests
will most likely be tailored to fit the code changes. If the code
changes are wrong (e.g. they contains bugs), the tests will most
likely not catch these bugs.
How is software developed when the TDD paradigm is followed?
- Requirements are received. It could be requirements for a new feature or a bug report.
- The requirements are understood by the developer and tests are written based on the requirements.
- Code changes are done so that the tests pass which in turn means that the requirements are satisfied.
In the case of TDD, the code changes do not influence the tests. It's the other way around (i.e. the tests influence the code changes). Furthermore, the tests are influenced by the requirements which means that the code changes are also influenced by the requirements.
How could the tests be written before the code changes are done? It's
might seem like a "chicken 🐔 or the egg 🥚 problem" 😀.
It
should not be a problem to write the tests before the code changes are
done if we accept the fact that the tests will initially fail. They
will fail for different reasons. Let's give a few examples:
- The code to be tested does not exist.
- The code to be tested does not behave as it should according to the test.
The process of writing the tests first and having them fail, then doing the code changes and having the tests pass, and finally refactoring the code in order for it to be more performant is called Red-Green-Refactor or RGR. We start with the failing tests (indicated by the red color), then we do the code changes and the tests pass (indicated by the green color), finally we refactor the code so that it is more performant and the tests still pass.
Try using TDD in some of your next requirements. Start with simpler requirements and build your way to more complex ones.
If you enjoy my articles, please consider supporting me.