JUnit 5 Tag-Based Test Selection and Filtering in CI Pipelines

JUnit 5 Tag-Based Test Selection and Filtering in CI Pipelines

JUnit 5 @Tag lets you label tests and select subsets at run time. Tag unit tests separately from integration and end-to-end tests, then configure your CI pipeline to run fast tests on every commit and slow tests on pull request merge or nightly. This post covers @Tag syntax, tag expressions (AND, OR, NOT), Maven Surefire and Gradle configuration, and a CI strategy that gives you fast feedback without skipping coverage.

A test suite that takes 20 minutes to run stops being used. Developers skip it locally and wait for CI. CI queues back up. Feedback loops lengthen. The fix isn't fewer tests — it's smarter test selection.

JUnit 5 tags let you annotate tests by category, then select exactly the category you need at run time. Unit tests on every save, integration tests on every commit, end-to-end tests on merge to main.

@Tag Basics

Apply @Tag to a test class or a test method:

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("unit")
class DiscountCalculatorTest {

    @Test
    void applyPercentageDiscount_shouldReducePrice() { ... }

    @Test
    void applyFixedDiscount_shouldReducePrice() { ... }
}

All tests in the class inherit the unit tag. You can also apply tags at the method level:

class OrderServiceTest {

    @Test
    @Tag("unit")
    void calculateTotal_shouldSumLineItems() { ... }

    @Test
    @Tag("integration")
    @Tag("slow")
    void createOrder_shouldPersistToDatabase() { ... }
}

Method-level tags augment but don't replace class-level tags. A test with a class-level @Tag("integration") and a method-level @Tag("slow") has both tags.

Tag Naming Conventions

Tags are arbitrary strings, but a consistent convention matters. Common patterns:

By test type:

unit          — no I/O, no framework, pure logic
integration   — hits real databases, message queues, file systems
e2e           — full stack, browser or API-level
contract      — Pact or other contract tests

By speed:

fast          — under 100ms
slow          — over 1 second

By environment dependency:

requires-db
requires-kafka
requires-network

By CI stage:

smoke         — minimal suite, must pass before anything else
regression    — full regression, runs on merge

Pick a convention and enforce it. Tags without discipline become noise.

Creating Tag Meta-Annotations

Repeating @Tag("integration") everywhere is verbose. Define meta-annotations once:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Tag("integration")
public @interface IntegrationTest {}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Tag("unit")
public @interface UnitTest {}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Tag("slow")
@Tag("integration")
public @interface SlowIntegrationTest {}

Usage:

@IntegrationTest
class UserRepositoryTest { ... }

@UnitTest
class UserServiceTest { ... }

Cleaner, and changing the tag value means changing one place.

Running Tagged Tests with Maven Surefire

The Maven Surefire Plugin (3.x) supports JUnit 5 tag filtering natively:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.5</version>
    <configuration>
        <groups>unit</groups>
        <excludedGroups>integration,e2e</excludedGroups>
    </configuration>
</plugin>

Or pass tags from the command line:

# Run only unit tests
mvn test -Dgroups=unit

# Run unit and integration tests
mvn test -Dgroups="unit | integration"

# Run everything except e2e
mvn test -DexcludedGroups=e2e

The groups parameter accepts tag expressions (covered below). excludedGroups takes the same syntax for exclusion.

Running Tagged Tests with Gradle

In build.gradle (Groovy DSL):

test {
    useJUnitPlatform {
        includeTags 'unit'
        excludeTags 'integration', 'e2e'
    }
}

task integrationTest(type: Test) {
    useJUnitPlatform {
        includeTags 'integration'
    }
    shouldRunAfter test
}

Kotlin DSL:

tasks.test {
    useJUnitPlatform {
        includeTags("unit")
        excludeTags("integration", "e2e")
    }
}

tasks.register<Test>("integrationTest") {
    useJUnitPlatform {
        includeTags("integration")
    }
    shouldRunAfter(tasks.test)
}

Run specific tasks:

./gradlew test           # unit tests only
./gradlew integrationTest  # integration tests only
./gradlew check          # all configured test tasks

Tag Expressions

Both Maven and Gradle accept tag expressions — boolean logic on tags:

Syntax Meaning
unit Tests tagged "unit"
`unit integration`
unit & fast Tests tagged both "unit" AND "fast"
!e2e Tests NOT tagged "e2e"
integration & !slow Integration tests that are not slow
`(unit integration) & !slow`

Examples:

# Maven: run fast unit and fast integration tests
mvn test -Dgroups="(unit | integration) & fast"

# Maven: everything except slow and e2e
mvn test -DexcludedGroups="slow | e2e"

Tag expressions give you flexible CI stage definitions without restructuring your test code.

CI Pipeline Strategy

Here's a practical three-stage CI strategy:

Stage 1: On every commit (fast feedback, < 2 minutes)

# GitHub Actions
- name: Unit Tests
  run: mvn test -Dgroups=unit

Catches logic errors immediately. Fails fast before any integration resources spin up.

Stage 2: On pull request (integration feedback, < 10 minutes)

- name: Integration Tests
  run: mvn test -Dgroups="unit | integration"

Covers database interactions, external service calls (via Testcontainers), and cross-component behavior.

Stage 3: On merge to main or nightly (full confidence)

- name: Full Test Suite
  run: mvn test  # no tag filter, runs everything

Includes end-to-end tests, contract tests, performance tests. Slow but comprehensive.

GitHub Actions Full Example

name: CI

on:
  push:
    branches: ['**']
  pull_request:
    branches: [main]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
      - name: Run unit tests
        run: mvn test -Dgroups=unit --no-transfer-progress

  integration-tests:
    runs-on: ubuntu-latest
    needs: unit-tests
    if: github.event_name == 'pull_request'
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
      - name: Run integration tests
        run: mvn test -Dgroups=integration --no-transfer-progress

  e2e-tests:
    runs-on: ubuntu-latest
    needs: integration-tests
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
      - name: Run E2E tests
        run: mvn test -Dgroups=e2e --no-transfer-progress

Unit tests block all other work. Integration tests only run on PRs. E2E tests only run on main. Each stage depends on the previous passing.

junit-platform.properties for Defaults

You can set default tag filters in src/test/resources/junit-platform.properties:

# Run all tags by default unless overridden
junit.jupiter.extensions.autodetection.enabled=true

# Exclude slow tests unless explicitly included
# (set this in CI with system properties to override)
junit.jupiter.conditions.deactivate=org.junit.jupiter.engine.extension.DisabledCondition

Or configure default included/excluded tags in your build tool rather than in properties, since build tool configuration is more visible and easier to override per-environment.

Tagging Inherited Test Methods

Tags on abstract base test classes are inherited. This is useful for creating typed integration test bases:

@Tag("integration")
@Tag("requires-db")
@ExtendWith(DatabaseExtension.class)
public abstract class AbstractDatabaseTest {
    // shared database setup
}

class UserRepositoryTest extends AbstractDatabaseTest {
    // automatically tagged "integration" and "requires-db"
    @Test
    void findById_shouldReturnUser() { ... }
}

This is a clean way to enforce tagging policy — if a test extends AbstractDatabaseTest, it's always tagged as an integration test that requires a database.

Verifying Tag Coverage

Periodically verify that your tagging is consistent. A quick check with Maven:

# How many tests in each category?
mvn test -Dgroups=unit -q && grep -E "Tests run:" target/surefire-reports/*.txt
mvn test -Dgroups=integration -q && grep -E "Tests run:" target/surefire-reports/*.txt

Or add a CI check that fails if untagged tests exist (requires a custom JUnit 5 extension that inspects tags during test execution and fails tests with no tags).

Summary

@Tag is the mechanism for building tiered CI test pipelines in JUnit 5. Apply tags by test type (unit, integration, e2e), speed (fast, slow), or environment dependency (requires-db). Use meta-annotations to avoid repeating tag strings. Configure Maven Surefire or Gradle to run tagged subsets, and use tag expressions (AND, OR, NOT) for precise selection. Structure your CI pipeline around three stages: unit tests on every commit, integration tests on PR, full suite on merge to main. This keeps feedback loops short without sacrificing test coverage.

Read more

Start now free