Reasons to Write Unit Tests
Learn why it is important to perform unit testing for production-ready code.
We'll cover the following
Let’s consider a hypothetical for a moment. Say that Pat has just completed work on a small feature change where they added a couple of dozen lines to the system. They are fairly confident in this change, but it has been a while since they have tried things out in the deployed system. Pat runs the build script, which packages and deploys the change to the local webserver. They pull up the application in their browser, navigate to the appropriate screen, enter a bit of data, click submit, and…stack trace!
Scenario: Manual and unit testing
Now let’s think about unit testing with a scenario.
Alex favors unit testing and would like to complete their project as easily as possible. Each time they write a small bit of code, they add a unit test that verifies the small change they added to the system. They then run all their unit tests, which only take a few seconds. This way, they don’t have to wait long to find out whether or not they can move on.
If there’s a problem, Alex stops immediately and fixes it. Their problems are easier to uncover because they’ve added only a few lines of code each time instead of piling loads of new code on top of their mistakes.
Alex retains the tests permanently, along with the rest of the system, which continues to pay off each time they or anyone else changes the code in the same area. These unit tests support regression testing as Alex no longer needs to spend several minutes verifying that new changes don’t break existing behaviors.
Alex’s tests also save their team significant amounts of time in understanding what the system does. If one of their teammates asked how the system handles the combination of X and Y, a developer using manual testing would likely reply “I don’t know, let me take a look at the code.” They may have an answer in a minute or two, but frequently they end up digging for much longer. Meanwhile, someone using unit testing could simply look at their unit tests for an immediate answer.
Let’s follow in Alex’s footsteps and start learning how to write small, focused unit tests. First, we’ll make sure we understand basic JUnit concepts.