0
0
JUnittesting~8 mins

Custom display names for parameters in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Custom display names for parameters
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── Application.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── tests/
│               │   └── ParameterizedTests.java
│               ├── utils/
│               │   └── TestUtils.java
│               └── config/
│                   └── TestConfig.java
└── pom.xml
  
Test Framework Layers
  • Test Classes: Contain parameterized tests using JUnit 5 annotations like @ParameterizedTest and @MethodSource with custom display names.
  • Test Data Providers: Methods supplying parameters with descriptive names for clarity in test reports.
  • Utilities: Helper methods for formatting display names or generating test data.
  • Configuration: Setup for test environment, e.g., test properties or profiles.
Configuration Patterns

Use @MethodSource to provide parameters with custom display names. Define data provider methods returning Stream<Arguments> where each Arguments includes the parameter and a descriptive name.

Example pattern for custom display names:

  @ParameterizedTest(name = "Test with input={1}")
  @MethodSource("provideTestData")
  void testWithCustomName(String input, String displayName) {
      // test code
  }

  static Stream<Arguments> provideTestData() {
      return Stream.of(
          Arguments.of("apple", "fruit: apple"),
          Arguments.of("carrot", "vegetable: carrot")
      );
  }
  

This pattern helps tests show meaningful names in reports and IDE runners.

Test Reporting and CI/CD Integration
  • JUnit 5's custom display names appear in IDE test runners and build tools like Maven Surefire or Gradle Test Logger.
  • CI servers (Jenkins, GitHub Actions) show these names in test reports, improving readability.
  • Integrate with reporting tools like Allure or Surefire reports to capture display names for better traceability.
Best Practices
  1. Always use @ParameterizedTest(name = "...") to define clear, descriptive test names.
  2. Provide a second parameter for display names in your data provider to keep test logic and naming separate.
  3. Keep display names short but meaningful to quickly understand test purpose.
  4. Use Arguments.of() to bundle parameters and names together cleanly.
  5. Ensure display names do not contain sensitive data to keep reports safe.
Self Check

Where in this folder structure would you add a new data provider method that supplies parameters with custom display names for a new feature test?

Key Result
Use JUnit 5 parameterized tests with @ParameterizedTest(name=...) and @MethodSource to provide custom display names for parameters.