Test naming conventions deep dive in JUnit - Build an Automation Script
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @DisplayName("Calculator Tests with Naming Conventions") public class CalculatorTest { private final Calculator calculator = new Calculator(); @Test @DisplayName("Should return sum when both numbers are positive") void shouldReturnSumWhenBothNumbersArePositive() { int result = calculator.add(3, 5); assertEquals(8, result); } @Test @DisplayName("Should throw exception when divisor is zero") void shouldThrowExceptionWhenDivisorIsZero() { assertThrows(ArithmeticException.class, () -> { calculator.divide(10, 0); }); } @Test @DisplayName("Should return negative result when subtracting larger from smaller") void shouldReturnNegativeResultWhenSubtractingLargerFromSmaller() { int result = calculator.subtract(3, 10); assertTrue(result < 0); assertEquals(-7, result); } } // Supporting class for context class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int divide(int a, int b) { if (b == 0) throw new ArithmeticException("Division by zero"); return a / b; } }
This test class demonstrates proper JUnit 5 test naming conventions using two complementary approaches.
Method naming: Each test method uses the shouldDoSomethingWhenCondition pattern. For example, shouldReturnSumWhenBothNumbersArePositive clearly states the expected behavior and the condition being tested.
@DisplayName annotation: JUnit 5 provides @DisplayName to add human-readable descriptions that appear in test reports. This is useful when method names would become too long or when you want spaces and special characters in the description.
Why this matters: When a test fails, the name alone should tell you what went wrong. A failure in shouldThrowExceptionWhenDivisorIsZero immediately communicates the issue without reading the test body.
Each test follows AAA pattern: Arrange the input, Act by calling the method, Assert the expected outcome. Combined with clear naming, this makes tests self-documenting.
Add a @Nested inner class named WhenInputIsNull with tests that follow naming conventions for null input edge cases