John had made a simple typo on line 4. Instead of checking for equality, he had set z to true, meaning the program always returned 0.

Of course, John had used this method dozens of times in other methods, which then were used in even more methods. With the bug nested several functions deep, John lost several nights of sleep until he discovered the mistake.

Scenarios like these are common, and could have been avoided by unit testing.

What is unit testing?

Unit testing is essentially breaking your application into tiny tiny parts, and testing each of those parts to make sure they work properly. All of these tests are separate, and ensure that your code functions as it should.

Higher-level functions depend on lower-level functions, so by testing those lower-level functions, you can ensure that any function x that depends on a function y will run smoothly. Unit testing will allow you to be confident that your function y works correctly, and that any method that depends on function y will also work correctly, as long as the logic is correct. In addition, if function x is tested, and function y is changed, you can be sure that your change doesn’t break function x as long as all the tests pass. Having key functions tested will allow you to confidently and safely revise code without fear of causing random bugs in other parts of the software.

“But Henry! I don’t have time to do unit testing. It takes up too much time!”

While this is a common argument against unit testing, and may hold true for tiny projects, unit tests pay off in the long run by several magnitudes. Although you might initially make much faster progress by neglecting unit tests, your code will ultimately be buggier and less stable, which in turn, will drain huge chunks of your time and ruin your productivity. By doing unit tests, your progress will be almost linear throughout the project because you will spot bugs before they become dozens of layers deep in your code. In addition, you can safely refactor without breaking any functionality, which reduces code rot, increases productivity, and improves the quality of your code base.

Unit tests are an efficient and easy way to decrease the number of bugs in your code, which would otherwise cause long nights with caffeine. Writing unit tests can boost your confidence in your code, and if you can’t trust that your code works, then what can you trust?