JUnit 5 Tagging and Filtering, @Tag examples
This article shows you how to use the JUnit 5 tagging and filtering via the @Tag
annotation.
Tested with
- JUnit 5.5.2
- Maven 3.6.0
- Gradle 5.6.2
1. @Tag
A simple tagging for demo.
TagMethodTest.java
package com.mkyong.tags;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Tag("branch-20")
public class TagMethodTest {
@Test
@Tag("feature-168")
void test1Plus1() {
assertEquals(2, 1 + 1);
}
@Test
@Tag("integration")
@Tag("fast")
void testFastAndIntegration() {
assertEquals(2, 1 + 1);
}
@Test
@Tag("slow")
void testSlow() {
assertEquals(2, 1 + 1);
}
}
2. Maven filtering tests
2.1 In Maven, we can run tests based on tags via the configuration parameters of the maven-surefire-plugin
pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<!-- include tags -->
<groups>integration, feature-168</groups>
<!-- exclude tags -->
<excludedGroups>slow</excludedGroups>
</configuration>
</plugin>
2.2 In console, uses -D
option.
Terminal
# Run tests which tagged with `integration, slow, feature-168`
$ mvn -Dgroups="integration, fast, feature-168"
# Exclude tests which tagged with 'slow'
$ mvn -DexcludedGroups="slow"
3. Gradle filtering tests
3.1 In Gradle, we can filter the tags like this:
build.gradle
test {
useJUnitPlatform{
includeTags 'integration', 'feature-168'
excludeTags 'slow'
}
}
Run tests which tagged with integration' and `feature-168
Terminal
$ gradle clean test
> Task :test
com.mkyong.tags.TagMethodTest > testFastAndIntegration() PASSED
com.mkyong.tags.TagMethodTest > test1Plus1() PASSED
3.2 No idea how to pass the includeTags
parameters in the console, creates a new test task instead.
build.gradle
task slowTest(type: Test) {
useJUnitPlatform {
includeTags 'slow'
}
}
Run tests which tagged with ‘slow’
Terminal
$ gradle clean slowtest
> Task :slowTest
com.mkyong.tags.TagMethodTest > testSlow() PASSED
Note
JUnit 5 supports Tag Expressions.
JUnit 5 supports Tag Expressions.
Download Source Code
$ git clone https://github.com/mkyong/junit-examples
$ cd junit5-examples
$ check src/test/java/com/mkyong/tag/*.java
$ check pom.xml, uncomment tags stuff
$ mvn test
$ check build.gradle, uncomment tags stuff
$ gradle test
$ cd junit5-examples
$ check src/test/java/com/mkyong/tag/*.java
$ check pom.xml, uncomment tags stuff
$ mvn test
$ check build.gradle, uncomment tags stuff
$ gradle test
thx, but does anyone know hot to set the include/exclude tags in the gradle cmd? Equivalent to
mvn test -Dgroups="slow"
???I noticed that for the “2.2 In console, uses -D option” to work, it is required to at least including the maven-surefire-plugin in the pom.xml.
Instead of using @Tag – is it possible to set a custom annotation and use it in the pom file?
thank you