0
0
JUnittesting~8 mins

Selecting tests by tags and classes in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Selecting tests by tags and classes
Folder Structure
src/
└── test/
    └── java/
        ├── com/
        │   └── example/
        │       ├── tests/
        │       │   ├── LoginTests.java       # Test classes with tags
        │       │   ├── PaymentTests.java
        │       │   └── UserProfileTests.java
        │       ├── pages/
        │       │   └── LoginPage.java        # Page Object classes
        │       └── utils/
        │           └── TestUtils.java        # Utility classes
    └── resources/
        └── junit-platform.properties       # Configuration for tags
Test Framework Layers
  • Test Classes: Contain test methods annotated with @Test and tagged with @Tag annotations to group tests logically.
  • Page Objects: Encapsulate UI elements and actions for maintainability and reuse.
  • Utilities: Helper methods for common tasks like data setup or assertions.
  • Configuration: Properties files or annotations to control which tags or classes to run.
  • Test Runner: JUnit Platform Launcher or build tool (Maven/Gradle) configured to select tests by tags or classes.
Configuration Patterns

Use junit-platform.properties file in src/test/resources to define which tags to include or exclude during test runs.

junit.jupiter.tags.include = fast, login
junit.jupiter.tags.exclude = slow

Alternatively, configure Maven Surefire Plugin or Gradle Test task to select tests by tags or classes.


<configuration>
  <groups>fast,login</groups>
</configuration>

Or run tests from command line specifying tags:

mvn test -Dgroups=fast
Test Reporting and CI/CD Integration
  • Use JUnit XML reports generated by Maven or Gradle for CI tools like Jenkins, GitHub Actions, or GitLab CI.
  • Reports show which tests ran, their tags, and pass/fail status.
  • CI pipelines can run different test suites by tags, e.g., run only @Tag("smoke") tests on pull requests.
  • Fail fast or rerun failed tests based on tag selection to optimize feedback time.
Best Practices
  1. Use meaningful tags: Tag tests by feature, priority, or speed (e.g., fast, slow, smoke).
  2. Keep tags consistent: Define a tagging strategy and document it for the team.
  3. Combine tags and classes: Use tags for logical grouping and classes for technical grouping.
  4. Configure tag filters centrally: Use junit-platform.properties or build tool config to avoid duplication.
  5. Integrate with CI: Use tag selection to run relevant tests in different pipeline stages.
Self Check

Where in this folder structure would you add a new test class for "OrderProcessingTests" that should be tagged as @Tag("payment")?

Key Result
Organize JUnit tests with @Tag annotations and configure test runs by tags or classes for flexible selection.