Catching Common Errors and Asserting Exceptions

Let's identify common errors and assert exceptions, enhancing test quality and reliability.

Catching common errors

The traditional view of testing is of it as a process to check that code works as it is intended to work. Unit tests excel at this and automate the process of running the code with known inputs and checking for expected outputs. As we are human, all of us make mistakes from time to time as we write code and some of these can have significant impacts. There are several common simple mistakes we can make and unit tests excel at catching them all. The most likely errors are the following:

  • Off-by-one errors

  • Inverted conditional logic

  • Missing conditions

  • Uninitialized data

  • The wrong algorithm

  • Broken equality checks

Lowercase example

As an example, going back to our earlier test for a lowercase username, suppose we decided not to implement this using the String built-in .toLowerCase() method, but instead tried to roll our own loop code, like this:

Get hands-on with 1200+ tech skills courses.