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 [book_osherove]The Art of Unit Testing[/book_osherove], provides a good unit test naming convention that incorporates these three elements.
In his blog post “Naming standards for unit tests” he describes it like this:
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.
Programming was fun when I was a kid. But working in Silicon Valley, I saw poor code lead to fear, with real human costs. Looking for ways to make my life better, I learned about Design Patterns, Refactoring, and Test-Driven Development (TDD). Programming became fun again! I've now been doing TDD in Apple environments for 18 years. I'm committed to software crafting as a discipline, hoping we can all reach greater effectiveness and joy.
Please log in again. The login page will open in a new tab. After logging in you can close it and return to this page.