Catching Common Errors and Asserting Exceptions

Learn to identify common errors and assert exceptions, enhancing test quality and reliability.

Catching common errors

The traditional view of testing is to think of it as a process to check that code works as intended. Unit tests excel at this and automate the process of running the code with known inputs and checking for expected outputs. As we’re 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

  • Wrong algorithm

  • Broken equality checks

Lowercasing username example

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

Get hands-on with 1200+ tech skills courses.