0
0
JUnittesting~15 mins

@Tag for categorization in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify test execution filtering using @Tag annotation
Preconditions (2)
Step 1: Run tests with the tag filter set to 'fast'
Step 2: Observe which tests are executed
Step 3: Run tests with the tag filter set to 'slow'
Step 4: Observe which tests are executed
✅ Expected Result: Only tests with the specified tag are executed in each run
Automation Requirements - JUnit 5
Assertions Needed:
Verify that tests with the selected tag run
Verify that tests without the selected tag do not run
Best Practices:
Use @Tag annotation on test methods for categorization
Use JUnit 5's built-in tag filtering to run specific groups
Keep test methods independent and clearly tagged
Automated Solution
JUnit
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class TagExampleTest {

    @Test
    @Tag("fast")
    void fastTest() {
        assertTrue(true, "Fast test should always pass");
    }

    @Test
    @Tag("slow")
    void slowTest() {
        assertTrue(true, "Slow test should always pass");
    }

    @Test
    void untaggedTest() {
        assertTrue(true, "Untagged test should always pass");
    }
}

/*
To run tests with tag 'fast', use:

mvn test -Dgroups=fast

or configure your IDE or build tool to include only @Tag("fast") tests.

This example shows how to categorize tests and run them selectively.
*/

This code defines three test methods: one tagged as fast, one as slow, and one without any tag.

The @Tag annotation categorizes tests. You can run tests filtered by these tags using your build tool or IDE settings.

Assertions simply verify the tests run and pass. The untagged test runs unless filtered out.

This setup helps organize tests by speed or type, making test runs faster and more focused.

Common Mistakes - 3 Pitfalls
Not using @Tag annotation on test methods
{'mistake': "Using the same tag name inconsistently (e.g., 'Fast' vs 'fast')", 'why_bad': 'Tag filtering is case-sensitive, so inconsistent tags cause unexpected test runs.', 'correct_approach': 'Use consistent lowercase tag names throughout the project.'}
Trying to filter tests without configuring the build tool or IDE
Bonus Challenge

Add tests with multiple tags and run tests that match any of the tags

Show Hint