Good test names are one of the highest-value investments you can make in a test suite. A test named test1() tells you nothing when it fails at 2am. A test named shouldThrowIllegalArgumentExceptionWhenEmailIsNull tells you exactly what broke, why it matters, and where to look. This guide covers every JUnit 6 test naming convention and strategy β from method names and @DisplayName to display name generators and custom naming strategies.
Why Test Naming Matters
Test names serve as living documentation. They communicate:
- What is being tested (the method or feature)
- When β under what conditions
- What is expected to happen
A well-named test suite is searchable, self-documenting, and produces build reports that any developer β or product owner β can read and understand without opening the source code.
Strategy 1: The Should-When Pattern
The most widely adopted Java test naming convention. The method name reads as a sentence: "should [expected behaviour] when [condition]."
class PasswordValidatorTest {
// Pattern: should[ExpectedBehaviour]When[Condition]
@Test
void shouldReturnTrueWhenPasswordMeetsAllRequirements() { }
@Test
void shouldReturnFalseWhenPasswordIsShorterThanEightCharacters() { }
@Test
void shouldThrowIllegalArgumentExceptionWhenPasswordIsNull() { }
@Test
void shouldRequireAtLeastOneUppercaseLetter() { }
@Test
void shouldRequireAtLeastOneSpecialCharacter() { }
}
Strategy 2: The Given-When-Then Pattern (BDD Style)
Derived from Behaviour-Driven Development (BDD). Works well in teams that also write Gherkin-style specifications:
class ShoppingCartTest {
// Pattern: given[Context]_when[Action]_then[ExpectedOutcome]
// Underscores are allowed in test method names β JUnit 6 accepts them
@Test
void givenEmptyCart_whenAddingFirstItem_thenCartContainsOneItem() { }
@Test
void givenCartWithItems_whenApplyingValidCoupon_thenTotalIsReduced() { }
@Test
void givenCartWithItems_whenApplyingExpiredCoupon_thenExceptionIsThrown() { }
@Test
void givenCartAtMaxCapacity_whenAddingAnotherItem_thenCartFullExceptionIsThrown() { }
}
Continue reading JUnit 6 Test Naming Conventions for Readable and Maintainable Tests
