The @Tag annotation in JUnit 5 provides a flexible way to categorize and organize tests. Unlike JUnit 4's category system which required custom annotations and had limited filtering options, @Tag uses simple string values that can be applied at both class and method levels.
Purpose and Benefits
Tags allow you to group tests based on various criteria such as test type (unit, integration, end-to-end), execution speed (fast, slow), feature area, or any custom classification. This enables selective test execution during different phases of development or in specific environments.
JUnit 4 vs JUnit 5 Approach
In JUnit 4, test categorization required creating custom annotation interfaces and had complex configuration. JUnit 5 simplifies this with plain string tags that are easier to manage and more flexible for build tool integration.
Java source and doc
Definition of Tag(Version: junit-5 5.0.0) package org.junit.jupiter.api;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Tags.class)
@API(status = STABLE, since = "5.0")
public @interface Tag {
String value();
1
}
As seen in above definition @Tag can be applied both on class level and method level (@Target({ ElementType.TYPE, ElementType.METHOD })).
In next tutorials we will see how to use @Tag annotation, what is the difference between class level tagging and method level tagging, and how to perform filtering.
|