In this tutorial, we are going to learn how to Tag Tests using JUnit Jupiter tests.

Test classes and methods can be tagged in the JUnit 5 programming model by means of the annotation @Tag. Those tags can later be used to filter test discovery and execution. In this example, we see the use of @org.junit.jupiter.api.Tag at class level and also at method level.

package com.example;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Tag;

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

 
@Tag("all")
public class AppTest 
{

    @Test
    @Tag("development")

    void testOne() {
        assertEquals("ok","ok");
    }

    @Test
    @Tag("production")
    void testTwo() {
        assertEquals("ok","ok");
    }

    @Test
    @Tag("performance")
    void testThree() {
        assertEquals("ok","ok");
    }

}

Now how to choose which of the tagged Tests can be executed? There are two simple ways: one is specifying in the maven-surfire plugin which Test Tags we want to execute:

        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
          <configuration>
            <groups>production</groups>
          </configuration>
        </plugin>

Another option is to use a simple TestSuite class which uses the @IncludeTags to specify the list of @Tag Tests:

package com.example;

import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.IncludeTags;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
@SelectPackages("com.example")
@IncludeTags("all")
public class TestSuiteDemo {
}

For example, if we were to run this TestSuite, we would fire all tests, as the "all" Tag has been placed at Class level:

junit jupiter tags tutorial tag

FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials