To run only selected JUnit 5 tests by tag, mark your tests with @Tag, then configure your build tool or IDE to include only that tag.
1. Add tags to your tests
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class PaymentServiceTest {
@Test
@Tag("fast")
void calculatesTotal() {
// test code
}
@Test
@Tag("integration")
void connectsToPaymentGateway() {
// test code
}
}
You can also tag an entire test class:
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("integration")
class UserRepositoryTest {
@Test
void savesUser() {
// test code
}
}
All tests in that class inherit the integration tag.
2. Run tagged tests with Maven
If you use Maven Surefire, run tests with a specific tag like this:
mvn test -Dgroups=integration
To run multiple tags:
mvn test -Dgroups="fast,integration"
To exclude a tag:
mvn test -DexcludedGroups=slow
Example Maven configuration:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
</plugins>
</build>
3. Run tagged tests with Gradle
For Gradle, configure the test task:
tasks.test {
useJUnitPlatform {
includeTags 'integration'
}
}
Then run:
gradle test
You can include multiple tags:
tasks.test {
useJUnitPlatform {
includeTags 'fast', 'integration'
}
}
Or exclude tags:
tasks.test {
useJUnitPlatform {
excludeTags 'slow'
}
}
You can also pass tags from the command line:
tasks.test {
useJUnitPlatform {
if (project.hasProperty('includeTags')) {
includeTags project.property('includeTags').split(',')
}
}
}
Then run:
gradle test -PincludeTags=integration
4. Run tagged tests in IntelliJ IDEA
In IntelliJ IDEA:
- Open Run | Edit Configurations…
- Create or select a JUnit run configuration.
- Set Test kind to Tags.
- Enter the tag name, for example:
integration - Run the configuration.
You can use tag expressions such as:
fast & !slowor:
integration | smoke
Summary
| Tool | Example |
|---|---|
| JUnit annotation | @Tag("integration") |
| Maven | mvn test -Dgroups=integration |
| Gradle | includeTags 'integration' |
| IntelliJ IDEA | JUnit run configuration → Test kind: Tags |
Use tags like fast, slow, unit, integration, or smoke to organize your test suite and run only the tests you need.
