Testing your code is annoying, but the impact of not doing so can be orders of magnitude more annoying! In this article, we’ll use test-driven development to write and test our code more effectively.
What is Test-Driven Development?
Since the dawn of the computer era, programmers and bugs have battled for supremacy. It’s an inevitable occurrence. Even the greatest programmers fall prey to these anomalies. No code is safe. That’s why we do testing. Programmers, at least sane ones, test their code by running it on development machines to make sure it does what it’s supposed to.
Test-driven development is a programming technique that requires you to write actual code and automated test code simultaneously. This ensures that you test your code—and enables you to retest your code quickly and easily, since it’s automated.
How does it work?
Test-driven development, or TDD as we’ll call it from now on, revolves around a short iterative development cycle that goes something like this:
1. Before writing any code, you must first write an automated test for your code. While writing the automated tests, you must take into account all possible inputs, errors, and outputs. This way, your mind is not clouded by any code that’s already been written.
2. The first time you run your automated test, the test should fail—indicating that the code is not yet ready.
3. Afterward, you can begin programming. Since there’s already an automated test, as long as the code fails it, it means that it’s still not ready. The code can be fixed until it passes all assertions.
4. Once the code passes the test, you can then begin cleaning it up, via refactoring. As long as the code still passes the test, it means that it still works. You no longer have to worry about changes that introduce new bugs.
5. Start the whole thing over again with some other method or program.