0
0
JUnittesting~5 mins

@Tag for categorization in JUnit

Choose your learning style9 modes available
Introduction

The @Tag annotation helps group tests by categories. It makes running specific groups of tests easier.

You want to run only fast tests during development.
You want to separate integration tests from unit tests.
You want to run tests related to a specific feature.
You want to exclude flaky tests temporarily.
You want to organize tests by priority or team ownership.
Syntax
JUnit
@Tag("tagName")
@Test
void testMethod() {
    // test code
}

Place @Tag above test methods or test classes.

You can use multiple tags by repeating @Tag annotations.

Examples
This test is tagged as "fast" and can be run separately.
JUnit
@Tag("fast")
@Test
void quickTest() {
    // test code
}
This test is tagged as "integration" to identify it as an integration test.
JUnit
@Tag("integration")
@Test
void databaseTest() {
    // test code
}
This test has two tags: "slow" and "ui" for more specific grouping.
JUnit
@Tag("slow")
@Tag("ui")
@Test
void uiTest() {
    // test code
}
Sample Program

This class has two tests, each tagged differently. You can run only "fast" tests or only "slow" tests using these tags.

JUnit
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class SampleTagTest {

    @Tag("fast")
    @Test
    void fastTest() {
        assertTrue(1 + 1 == 2);
    }

    @Tag("slow")
    @Test
    void slowTest() {
        assertTrue(2 * 2 == 4);
    }

}
OutputSuccess
Important Notes

You can filter tests by tags in your build tool or IDE.

Tags help keep your test suite organized and efficient.

Summary

@Tag groups tests for easier selection.

Use tags to run or skip specific test categories.

Tags can be added to methods or whole classes.