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
Practice
Solution
Step 1: Understand the purpose of test naming
Good test names clearly describe what is tested and the expected outcome.Step 2: Evaluate each option
shouldReturnTrueWhenInputIsValid uses a descriptive style 'shouldReturnTrueWhenInputIsValid' which explains behavior and condition. Options B, C, and D are vague and do not describe the test purpose.Final Answer:
shouldReturnTrueWhenInputIsValid -> Option AQuick Check:
Descriptive test names = shouldReturnTrueWhenInputIsValid [OK]
- Using generic names like 'test1' or 'runTest'
- Not describing expected behavior
- Using too short or unclear names
Solution
Step 1: Recall JUnit 5 test method syntax
JUnit 5 test methods must be void, have no parameters, and be annotated with @Test (annotation not shown here but method signature matters).Step 2: Check method declarations
void shouldReturnFalseWhenInputIsNull() is a valid Java method signature. test shouldReturnFalseWhenInputIsNull() has invalid syntax with 'test' keyword. void shouldReturnFalseWhenInputIsNull misses parentheses. void shouldReturnFalseWhenInputIsNull[] uses invalid brackets.Final Answer:
void shouldReturnFalseWhenInputIsNull() -> Option CQuick Check:
Valid Java method syntax = void shouldReturnFalseWhenInputIsNull() [OK]
- Omitting parentheses in method declaration
- Adding invalid keywords before method name
- Using brackets instead of parentheses
whenUserIsAdmin_thenAccessGranted(), what does this naming style indicate?Solution
Step 1: Analyze the naming pattern
The name uses 'whenCondition_thenResult' style, describing the condition and expected outcome.Step 2: Interpret the meaning
'whenUserIsAdmin' is the condition, 'thenAccessGranted' is the expected result. So the test checks access granted for admin users.Final Answer:
The test checks that access is granted when the user is an admin -> Option AQuick Check:
whenCondition_thenResult = The test checks that access is granted when the user is an admin [OK]
- Confusing condition with expected result
- Assuming test denies access instead of granting
- Thinking test runs only for admin without checking outcome
testUserLoginSuccessSolution
Step 1: Examine the test name clarity
'testUserLoginSuccess' is vague; it does not explain what success means or under what condition.Step 2: Check naming conventions
Good names describe behavior and expected result clearly, e.g., 'shouldLoginSuccessfullyWithValidCredentials'. The given name lacks this clarity.Final Answer:
It lacks a clear description of the expected behavior -> Option DQuick Check:
Clear expected behavior needed = It lacks a clear description of the expected behavior [OK]
- Assuming underscores are disallowed (they are allowed)
- Thinking length alone is a problem
- Believing 'should' prefix is mandatory
Solution
Step 1: Identify key elements in the test scenario
The test checks payment failure due to invalid credit card number.Step 2: Evaluate each option for clarity and completeness
shouldFailPaymentForInvalidCardNumber clearly states expected behavior and condition. Options A, C, and D are less descriptive or ambiguous.Final Answer:
shouldFailPaymentForInvalidCardNumber -> Option BQuick Check:
Clear condition and expected result = shouldFailPaymentForInvalidCardNumber [OK]
- Using vague or incomplete names
- Omitting the condition or expected outcome
- Using generic prefixes without details
Ready to prove it?
Pass the test and this pattern moves unknown
