Home  >  JUnit 5

JUnit @Tag + Filter with Maven

By Arvind Rai, May 08, 2021
On this page we will learn using @Tag annotation in our JUnit tests. We will also learn filtering test classes and test methods using tags with Maven.
1. JUnit @Tag annotation is introduced in JUnit 5.
2. A @Tag is used at test class level as well as test method level.
3. We need to pass a tag name to @Tag annotation. Tag names are used to filter which tests are included or excluded for a given test plan.
4. The @Tag is repeatable annotation. It means we can use @Tag more than one time at method level as well as class level.
5. 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.
6. Tags can be filtered using build file such as Maven and Gradle. IDE can also be used to filter tags while running JUnit tests.

Technologies Used

Find the technologies being used in our example.
1. Java 14
2. JUnit 5.7.1
3. Maven 3.8.1

Using @Tag Annotation

Find the examples to use @Tag annotation.
public class MyAppTest1 {
  void additionTest() {
	int sum = 50 + 60;
	assertEquals(110, sum);
  void multiplyTest() {
	int multi = 15 * 5;
	assertEquals(75, multi);
public class MyAppTest2 {
  void additionTest() {
	int sum = 60 + 40;
	assertEquals(100, sum);
  void multiplyTest() {
	int multi = 20 * 5;
	assertEquals(100, multi);

Filter with Maven

1. Maven provides maven-surefire-plugin to execute the unit tests of an application. The reports are generated in *.txt and *.xml files. By default these reports are generated in below directory.
2. We can filter tests by tags or tag expressions. Here we will learn to filter test using Maven. In Maven,
a. To include tags or tag expressions, use <groups>
b. To exclude tags or tag expressions, use <excludedGroups>
Find the sample Maven code.
				<groups>integration | feature2</groups>
3. 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'.

4. We can run test files using Maven command as following.
a. Run only single test class, for ex. MyAppTest1
mvn -Dtest=MyAppTest1 test 
b. Run all test classes.
mvn -Dtest=* test 
Find the print screen of the output.
JUnit @Tag + Filter with Maven


Annotation Type Tag
Tagging and Filtering
Running a Single Test

Download Source Code


©2021 concretepage.com | Privacy Policy | Contact Us