Introduction
Many of us spend minutes or hours on coming up with a name for the unit test, and here I’d like to share my guidelines for unit test naming that I hope will make your tests easy to understand without diving into the details.
The problem
“Unit tests where each test case method name is only an enumeration, e.g. test1, test2, test3. As a result, the intention of the test case is unclear, and the only way to be sure is to read the test case code and pray for clarity.” - Yegor Bugaenko.
When I am working with unit tests I do not really want to dive into the test logic I just want to understand what it is testing as fast as possible. Thus, a unit a test name should tell the test story briefly.
Common Naming Conventions
While there is no universal rule for naming unit tests, several proven approaches exist and they are all about:
- Name of the method being tested
- Scenario under which the method is being tested
- Expected behavior when the scenario is invoked
Method-Scenario-Behavior (MSB Style) -
[MethodName]_[Scenario]_[ExpectedBehavior]
, example:Add_MaximumSumResult_ThrowsOverflowException()
.Given-When-Then (BDD Style) -
Given[InitialCondition]When[Action]Then[ExpectedResult]
, example:GivenEmptyString_WhenAdd_ThenReturnsZero()
Should Style -
[Method]Should[ExpectedBehavior]When[Scenario]
, example:AddShouldReturnZeroWhenEmptyString()
Useful tips
While there is no universal rule, there are universal tips instead:
- DO NOT write long names if possible.
- DO NOT use names like:
Test1
,Test2
,Test3
. - DO NOT lie. If the name doesn’t match reality, you made a mistake.
- Be intuitive. You write the name to understand what it is about as fast as possible.
- Ask someone for a review. The most reliable way to become confident in the test name - ask your colleague or someone else to try undestand what the test about only by the name.
- Use chosen name convention everywhere, it will be easier to work with tests if all of them named in the same way.