JUnit 5 @Tag can be used to filter testcases from test plans. It can help in create multiple different test plans for different environments, different use-cases or any specific requirement. You can execute set of tests by including only those tagged tests in test plan OR by excluding other tests from test plan.

@Tag Annotation Usage

You can apply the @Tag annotation on test class or test method or both.

@Tag("development")
public class ClassATest
{
	@Test
	@Tag("userManagement")
	void testCaseA(TestInfo testInfo) {
	}
}

You can apply multiple tags on single test case as well, so that you can include it in multiple test plans.

public class ClassATest
{
	@Test
	@Tag("development")
	@Tag("production")
	void testCaseA(TestInfo testInfo) {
	}
}

Create test plans with @IncludeTags and @ExcludeTags

You can use @IncludeTags or @ExcludeTags annotations in your testplan to filter tests or include tests.

//@IncludeTags example

@RunWith(JUnitPlatform.class)
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("production")
public class JUnit5Example 
{
}

//@ExcludeTags example

@RunWith(JUnitPlatform.class)
@SelectPackages("com.howtodoinjava.junit5.examples")
@ExcludeTags("production")
public class JUnit5Example 
{
}

To add more than one tag, pass a string array of tags in desired annotation.

@RunWith(JUnitPlatform.class)
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags({"production","development"})
public class JUnit5Example 
{
}
You CANNOT include both @IncludeTags and @ExcludeTags annotations in single test plan.

JUnit 5 @Tag Example

Let’s say we have 3 tests and we want to run all 3 in development environment; but want to run only one in production. So we will tag the tests as below:

public class ClassATest
{
	@Test
	@Tag("development")
	@Tag("production")
	void testCaseA(TestInfo testInfo) { //run in all environments
	}
}

public class ClassBTest
{
	@Test
	@Tag("development")
	void testCaseB(TestInfo testInfo) {
	}
}

public class ClassCTest
{
	@Test
	@Tag("development")
	void testCaseC(TestInfo testInfo) {
	}
}

Let’s create test plan for both environments.

Tests to run in production environment

@RunWith(JUnitPlatform.class)
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("production")
public class ProductionTests 
{
}
JUnit 5 @Tag Example - Production Tests
JUnit 5 @Tag Example – Production Tests

Tests to run in development environment

@RunWith(JUnitPlatform.class)
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("development")
public class DevelopmentTests 
{
}
JUnit 5 @Tag Example - Development Tests
JUnit 5 @Tag Example – Development Tests

Drop me your questions in comments section.

Happy Learning !!