0
0
JunitHow-ToBeginner ยท 3 min read

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 @Tag or using @Tags container.
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 @Tag only 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

FeatureDescription
@Tag("name")Assigns a tag to a test method or class
Multiple @Tag annotationsAssign multiple tags to a test
Test filteringRun tests by including/excluding tags via build tool or IDE
Class-level taggingTags apply to all test methods in the class
Tag namesCase-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.