0
0
JUnittesting~15 mins

Selecting tests by tags and classes in JUnit - Build an Automation Script

Choose your learning style9 modes available
Run JUnit tests filtered by tags and classes
Preconditions (2)
Step 1: Identify test classes with @Tag("fast") and @Tag("database")
Step 2: Configure the test runner to include only tests tagged with "fast"
Step 3: Run the tests
Step 4: Verify only tests with the "fast" tag are executed
Step 5: Configure the test runner to include tests from a specific test class named "UserServiceTest"
Step 6: Run the tests
Step 7: Verify only tests from the UserServiceTest class are executed
✅ Expected Result: When filtering by tag "fast", only tests with that tag run and pass. When filtering by class UserServiceTest, only tests from that class run and pass.
Automation Requirements - JUnit 5
Assertions Needed:
Verify that only tests with the specified tag are executed
Verify that only tests from the specified class are executed
Best Practices:
Use @Tag annotation to mark tests
Use JUnit Platform Launcher API or build tool configuration to filter tests by tags and classes
Avoid hardcoding test names; use tags and class names for maintainability
Use assertions to confirm test execution results
Automated Solution
JUnit
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.discovery.ClassSelector;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.engine.discovery.TagFilter;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.LauncherFactory;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class TestFilterByTagAndClass {

    @Tag("fast")
    public static class FastTests {
        @Test
        void fastTest1() {
            assertTrue(true);
        }
    }

    @Tag("database")
    public static class DatabaseTests {
        @Test
        void databaseTest1() {
            assertTrue(true);
        }
    }

    public static class UserServiceTest {
        @Test
        void userServiceTest1() {
            assertTrue(true);
        }
    }

    public static void main(String[] args) {
        runTestsByTag("fast");
        runTestsByClass(UserServiceTest.class);
    }

    private static void runTestsByTag(String tag) {
        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .filters(TagFilter.includeTags(tag))
                .build();

        Launcher launcher = LauncherFactory.create();
        SummaryGeneratingListener listener = new SummaryGeneratingListener();

        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);

        long testsFound = listener.getSummary().getTestsFoundCount();
        long testsSucceeded = listener.getSummary().getTestsSucceededCount();

        System.out.println("Tests run with tag '" + tag + "': " + testsFound);
        assertTrue(testsFound > 0, "No tests found with tag '" + tag + "'");
        assertTrue(testsFound == testsSucceeded, "Some tests with tag '" + tag + "' failed");
    }

    private static void runTestsByClass(Class<?> testClass) {
        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(DiscoverySelectors.selectClass(testClass))
                .build();

        Launcher launcher = LauncherFactory.create();
        SummaryGeneratingListener listener = new SummaryGeneratingListener();

        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);

        long testsFound = listener.getSummary().getTestsFoundCount();
        long testsSucceeded = listener.getSummary().getTestsSucceededCount();

        System.out.println("Tests run from class '" + testClass.getSimpleName() + "': " + testsFound);
        assertTrue(testsFound > 0, "No tests found in class '" + testClass.getSimpleName() + "'");
        assertTrue(testsFound == testsSucceeded, "Some tests in class '" + testClass.getSimpleName() + "' failed");
    }
}

This code defines three test classes with different tags and one without tags.

The runTestsByTag method builds a test request filtered by the given tag using TagFilter.includeTags. It runs the tests and asserts that some tests were found and all passed.

The runTestsByClass method builds a test request selecting only the specified test class. It runs the tests and asserts that some tests were found and all passed.

Using the JUnit Platform Launcher API allows us to programmatically select tests by tag or class, which is useful for automation and custom test runners.

Common Mistakes - 3 Pitfalls
Using hardcoded test method names instead of tags or classes
Not registering a TestExecutionListener to collect test results
Using deprecated JUnit 4 methods or annotations
Bonus Challenge

Now add data-driven testing with 3 different tag filters: 'fast', 'database', and 'slow'. Run tests for each tag and verify results.

Show Hint