JUnit 5 @Tag Annotation

JUnit 5 @Tag can be used to filter testcases from test suites. It can help in creating multiple different test suites for different environments, different use-cases or any specific requirement.

We can execute a set of tests by including only those tagged tests in the test plan OR by excluding other tests from the test plan.

1. @Tag Usage

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

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

We can apply multiple tags on a single test case as well so that you can include the test in multiple test suites.

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

2. Creating Suites with @IncludeTags and @ExcludeTags

We can use @IncludeTags or @ExcludeTags annotations in the suites to filter tests or include tests.

//@IncludeTags example

@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("production")
public class MultipleTagsExample
{
}

//@ExcludeTags example

@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@ExcludeTags("production")
public class MultipleTagsExample
{
}

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

@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags({"production","development"})
public class MultipleTagsExample
{
}

Note

We CAN NOT include both @IncludeTags and @ExcludeTags annotations in the same test suite.

3. JUnit 5 @Tag Example

Let’s say we have 3 tests and we want to run all 3 in the 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 two test suites – one for each environment.

Tests to run in production environment

@Suite
@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

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

Happy Learning !!

Sourcecode Download

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.