0
0
JUnittesting~8 mins

@ExtendWith annotation in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - @ExtendWith annotation
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── Application.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── extensions/
│               │   └── CustomExtension.java
│               ├── tests/
│               │   └── SampleTest.java
│               └── utils/
│                   └── TestUtils.java
└── pom.xml

This structure follows Maven conventions for a JUnit test project. The extensions folder holds custom extension classes used with @ExtendWith. Test classes are under tests.

Test Framework Layers
  • Extension Layer: Custom JUnit 5 extensions implementing interfaces like BeforeEachCallback, AfterEachCallback, etc. These are applied with @ExtendWith.
  • Test Layer: Test classes annotated with @Test and @ExtendWith to use extensions.
  • Utility Layer: Helper classes and methods to support tests and extensions.
  • Configuration Layer: Handles environment setup, test parameters, and extension configuration.
Configuration Patterns
  • Extension Registration: Use @ExtendWith(CustomExtension.class) on test classes or methods to register extensions.
  • Environment Properties: Use System.getProperty or @TestPropertySource to pass environment variables to extensions.
  • Parameter Resolution: Extensions can implement ParameterResolver to inject test data or mocks.
  • Profiles: Use Maven profiles or JUnit tags to run tests with different extension configurations.
Test Reporting and CI/CD Integration
  • JUnit 5 produces standard XML reports compatible with CI tools like Jenkins, GitHub Actions, or GitLab CI.
  • Extensions can log additional info or capture screenshots on failure for richer reports.
  • Integrate with build tools (Maven/Gradle) to run tests automatically on code commits.
  • Use CI pipelines to run tests with different extension configurations or environments.
Best Practices
  1. Single Responsibility: Each extension should do one thing, like logging, timing, or resource management.
  2. Reusable Extensions: Design extensions to be reusable across multiple test classes.
  3. Explicit Registration: Use @ExtendWith explicitly on test classes or methods for clarity.
  4. Parameter Injection: Use ParameterResolver to inject dependencies cleanly.
  5. Fail Fast: Extensions should fail tests quickly if preconditions are not met.
Self Check

Where in this folder structure would you add a new extension class that logs test execution time?

Key Result
Use @ExtendWith to register reusable JUnit 5 extensions that add behavior to tests cleanly and modularly.