Creating custom Tag in Junit5 based tests

Upasana | October 29, 2019 | 1 min read | 248 views | java junit


Junit 5 has concept of Tag which is used for filtering tests during execution. Further, Junit Jupiter annotations can be used as meta-annotations i.e. instead of copying and pasting @Tag("security") throughout your code base, you can create a custom composed annotation named @Security as follows.

Creating meta-annotation in Junit Jupiter
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("security")
public @interface Security {
}

Now, @Security can then be used as a drop-in replacement for @Tag("security"), as shown below:

Using custom tag meta-annotation
@Security
@Test
void mySecurityTest() {
    // ...
}

Infact, the Security annotation can be combined with @Test, as shown below:

meta-annotation @Test + @Tag("security")
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("security")
@Test
public @interface SecurityTest {
}

which can be used as follow:

Junit Jupiter testcase
@SecurityTest
void mySecurityTest() {
    // ...
}

Top articles in this category:
  1. Junit interview questions for SDET automation engineer
  2. 50 Java Interview Questions for SDET Automation Engineer
  3. Junit 5 Platform Launcher API
  4. Rest Assured API Testing Interview Questions
  5. JUnit 5 Parameterized Tests
  6. Migrating Spring Boot tests from Junit 4 to Junit 5
  7. Java Coding Problems for SDET Automation Engineer

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.