How many times have you run your tests, gotten a failure, and had to go digging through the test code to try to understand what it’s complaining about? For many of you, you’re so used to doing this that you don’t even notice it’s a problem.
Every time you have to read test code, precious time is lost. The feedback cycle lengthens, and you’re breaking your stride.
Remember, we are trying to go for fast feedback. When I run unit tests and get a failure, I want to understand what I just broke. And I want to do this without reading the test code.
Ideally, the test name alone gives me the information I need.
Consider a test named “testCalculateSalary”. Simple names like this are common in unit test tutorials, but I can’t recommend them in real code.
If this test fails, what do we know? We know that something has gone wrong in salary calculation. But beyond that, we can’t tell without looking.
So many questions we can’t answer without digging into the test code, and possibly the production code as well!
Instead, let’s put more information into the test name. When a test fails, I want to know three things:
Disclosure: The book links below are affiliate links. If you buy anything, I earn a commission, at no extra cost to you.
Roy Osherove, author of The Art of Unit Testing, provides a good unit test naming convention that incorporates these three elements.
In his blog post “Naming standards for unit tests” he describes it thus:
I have adopted this unit test naming convention, with slight changes:
All told, I apply Roy Osherove’s template to yield test names that look like this:
It may look odd to combine camel casing with underscores. Though unusual, I like how the underscores clearly separate the test name into its three components.
My test names don’t follow this template slavishly. If the unit of work is obvious (from the name of the test class), I may omit it. If the expected behavior is obvious, I may omit it. But whether explicit or implied, the three elements must be present without guesswork.
Whatever naming convention you choose, try to communicate the three parts. It may feel overly verbose, but there’s nothing wrong with having really long test names, as long as they’re clear.
How do you like to name your tests? Can you find any poorly named tests in your suite? Please share in the comments below.
Jon is a consultant on Clean Code for iOS, focusing on Test Driven Development, unit testing, refactoring, and design. He's been practicing TDD since 2001. You can learn more about his background, or see what services he can bring to your organization.
Please log in again. The login page will open in a new window. After logging in you can close it and return to this page.