0
0
JUnittesting~5 mins

Selecting tests by tags and classes in JUnit

Choose your learning style9 modes available
Introduction

We use tags and classes to run only certain tests we want. This saves time and helps focus on specific parts.

When you want to run only fast tests during development.
When you want to run tests related to a specific feature.
When you want to exclude slow or flaky tests from a run.
When you want to run tests from a specific test class only.
When you want to organize tests by categories for easier management.
Syntax
JUnit
mvn test -Dgroups="groupName"

// or using JUnit Platform Console Launcher
java -jar junit-platform-console-standalone.jar --select-package com.example --include-tag fast

// Using @Tag annotation in test class or method
@Tag("fast")
public class MyTest {
    @Test
    void testMethod() {}
}

Tags are added using the @Tag annotation on test classes or methods.

You can select tests by tags or by specifying test classes when running tests.

Examples
This test class is tagged as "fast". You can run only tests with this tag.
JUnit
@Tag("fast")
public class FastTests {
    @Test
    void quickTest() {}
}
This command runs tests tagged with "fast" using Maven Surefire plugin.
JUnit
mvn test -Dgroups="fast"
This runs all tests in the FastTests class using JUnit Console Launcher.
JUnit
java -jar junit-platform-console-standalone.jar --select-class com.example.FastTests
Sample Program

This class has two tests: one tagged "fast" and one tagged "slow". You can run only the "fast" test by selecting the tag.

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

@Tag("fast")
public class SampleTest {

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

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

You can add multiple tags to a test by repeating the @Tag annotation.

Use tags to group tests logically, like 'fast', 'slow', 'database', etc.

Selecting tests by class is useful when you want to run all tests in a specific file.

Summary

Tags help you run only the tests you want.

You add tags with @Tag on classes or methods.

You can run tests by tag or by test class name.