How to Use @Tag Annotation in JUnit for Test Grouping
In JUnit, use the
@Tag annotation to label tests with custom names for grouping. You can then run tests selectively by specifying these tags in your test runner or build tool configuration.Syntax
The @Tag annotation is placed above a test method or test class to assign one or more tags. Tags are simple strings used to group tests.
- @Tag("tagName"): Assigns a single tag.
- Multiple tags can be added by repeating
@Tagor using@Tagscontainer.
java
@Tag("fast") public void fastTest() { // test code } @Tag("slow") @Tag("database") public void slowDatabaseTest() { // test code }
Example
This example shows how to tag test methods and run only tests with a specific tag using JUnit 5.
java
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; public class TagExampleTest { @Test @Tag("fast") void fastTest() { System.out.println("Running fast test"); } @Test @Tag("slow") void slowTest() { System.out.println("Running slow test"); } }
Output
Running fast test
Running slow test
Common Pitfalls
Common mistakes when using @Tag include:
- Using tags inconsistently or with typos, causing filters to miss tests.
- Forgetting to configure the test runner or build tool to include/exclude tags.
- Applying
@Tagonly on methods but expecting class-level tags to apply.
Always verify tag names and test execution filters.
java
/* Wrong: Tag misspelled, so filter won't find it */ @Tag("fastt") void test() {} /* Right: Correct tag spelling */ @Tag("fast") void test() {}
Quick Reference
| Feature | Description |
|---|---|
| @Tag("name") | Assigns a tag to a test method or class |
| Multiple @Tag annotations | Assign multiple tags to a test |
| Test filtering | Run tests by including/excluding tags via build tool or IDE |
| Class-level tagging | Tags apply to all test methods in the class |
| Tag names | Case-sensitive strings, must match filter exactly |
Key Takeaways
Use @Tag to label tests for easy grouping and selective execution.
Tags are case-sensitive strings applied at method or class level.
Configure your test runner or build tool to include or exclude tags when running tests.
Avoid typos in tag names to ensure correct filtering.
Multiple tags can be assigned by repeating @Tag annotations.