Howard Paget
Projects
About

Writing Better Tests

Jun 02, 2022
testing

This series of articles covers some suggestions for writing better tests. These are not hard and fast rules just suggestions from examples of good and bad tests I’ve come across in the trenches. Before we list the tips let’s consider what is the purpose of the tests we write.

Purpose of tests

  • Document behaviour: A set of tests can provide concrete examples of how a classes and methods are used e.g. inputs and outputs, interactions with dependencies, etc. The great thing about this form of documentation is if it’s out-of-date the build will (optimistically) fail.

  • Show the presence of a bug: Some might say tests confirm that the software is working as expected however the tests only confirm it works for some given state and input as it’s unlikely you’ll have tests covering the full input space. In practice we use this bug presence detection in two ways:

    • Regression bugs: Typically we make a change then run the tests and if all is green we have some comfort that existing functionality is unchanged otherwise we investigate the failure.

    • Regular bugs: When a bug is identified an option for fixing it is to add a test for the case then make changes to get the test to pass.

Tips for writing good tests