Pitching Tests at the Right Level

Discover the comparative advantages of detailed and high-level test methods.

Introduction

There are numerous best practices associated with unit testing. For example, one of these is to include one assertion per test if possible. However, other best practices are more subjective. One of these practices is how many test methods to write to determine whether the application code behaves as expected. One approach is to write as many test methods to explicitly test individual, desired behaviors. Another approach is to write fewer test methods that test the functionality as a whole. Although writing fewer test methods is more succinct, this approach comes with the disadvantage of rendering the test cases more difficult to follow. This reduces the effectiveness of the test code as a means of documentation.

The two test method approaches

There are two high-level approaches to writing test methods:

  • The first approach details the exact pieces of specified behavior that underpin the higher-level behavior. This approach includes more test methods and will have more in-depth documentation.
  • The second approach is to focus on the higher-level behavior. This approach results in fewer test methods but also achieves a lower level of documentation.

Example of both approaches

Suppose some application code includes a DateIdentifier class, which identifies valid date formats. The following two examples will demonstrate the two test code approaches.

Detailed approach

The following test code includes comprehensive tests articulating explicitly which date formats the class tests. Each date recognition pattern is explicitly tested across eight separate test methods (lines 25, 36, 46, 53, 67, 83, 90, and 97). The test code is shown below:

Get hands-on with 1200+ tech skills courses.