Howard Paget
Projects
About

Writing Better Tests: Give Tests Meaningful Names

Jun 02, 2022
testing

This article is part of a series about writing good tests go to the article listing all tips here.

During my career I’ve come across tests with names such as test17 or checkMethodName. The problem with these names is they provide very little (or no) information about what scenario they are testing. Without an understandable name when a test fails the test code itself will have to be examined. Poor test names can make it difficult to spot missing test cases.

Communicate the scenario

The test name should communicate the scenario that is being tested and what the expected result is. A naming convention I personally use is:

  • Action e.g. withdrawal of amount
  • State e.g. a balance < amount to with withdrawn
  • Expectation e.g. an error

For example the test of withdrawing too much from a balance could be called withdrawal_of_amount_larger_than_balance_causes_error.

Ideally the focus is on behaviour rather than implementation

Suppose we where writing a test to verify that when a deposit is made the account owner is sent a message, currently this message is put on a queue and asynchronously emailed to the user. We could name the test balance_service_writes_to_queue which refers to implementation details i.e. a balance service and a queue without expressing the behaviour. If the mechanism for notifying the the user is changed for example to use a http request the name is incorrect. A more behaviour focused name could be balance_owner_is_notified_on_deposit.

Consider replacing should with must, is, etc (or nothing!)

The word “should” is often used in test names e.g. discount_should_be_applied however “should” is typically used to indicate something is probably true rather than a solid assertion like discount_is_applied. Often “should” can be replaced with must or is or omitted entirely leaving a concrete statement of truth.

The same can be said for “check” which is frequently used in the same way as “should”.