JUnit Filter Tests using Gradle and @Tag
May 11, 2021
On this page we will learn filtering tags with Gradle. JUnit has introduced @Tag
annotation that can be used at class level as well as method level. The @Tag
accepts a tag name. The JUnit @Tag
is repeatable annotation. It means we can use @Tag
more than one time at method level as well as class level. Tag name should not contain white spaces. Tag name should not contain ISO control characters and reserved characters such as comma, left parenthesis, right parenthesis, ampersand, vertical bar, exclamation point.
Gradle uses
includeTags
and excludeTags
to filter tags. To enable JUnit test run in Gradle, it provides useJUnitPlatform()
.
Here on this page we will create some test classes using
@Tag
annotation and then we will create a Gradle file and filter tests.
Technologies Used
Find the technologies being used in our example.1. Java 14
2. JUnit 5.7.1
3. Gradle 7.0
Create Test Classes with @Tag
MyAppTest1.javapublic class MyAppTest1 { @Tag("feature2") @Test void additionTest() { int sum = 50 + 60; assertEquals(110, sum); } @Tag("integration") @Tag("feature1") @Test void multiplyTest() { int multi = 15 * 5; assertEquals(75, multi); } }
@Tag("integration") @Tag("acceptance") public class MyAppTest2 { @Tag("feature1") @Test void additionTest() { int sum = 60 + 40; assertEquals(100, sum); } @Test void multiplyTest() { int multi = 20 * 5; assertEquals(100, multi); } }
Create Gradle
Find the Gradle file to filter tests.build.gradle
plugins { id 'java' id 'eclipse' } repositories { mavenCentral() } dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.1' testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.7.1' } tasks.named('test') { useJUnitPlatform { includeTags 'integration | feature2' excludeTags 'feature1' } }
build.gradle
, use the command as following.
gradle clean test

*.xml
files for test classes in below directory.
${basedir}/build/test-results/test/
MyAppTest1
and MyAppTest2
files, following test result files will be created.
TEST-com.concretepage.MyAppTest1.xml TEST-com.concretepage.MyAppTest2.xm

Tag expression can be created using ! , & , | . To adjust operator precedence, use ( and ). JUnit also supports two special expressions i.e.
any()
and none()
.
any(): Selects all tests with any tags at all.
none(): Selects all tests without any tags.
feature1 : Selects all tests for 'feature1'.
integration | feature2 : Selects all tests for 'integration ' plus all tests for 'feature2'.
integration & feature2 : Selects all tests for the intersection between 'integration' and 'feature2'.
References
Tagging and FilteringAnnotation Type Tag