Creating custom Tag in Junit5 based tests

Carvia Tech | October 29, 2019 | 1 min read | 2 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. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: JUnit interview questions for automation engineer
  3. SDET: Rest Assured Interview Questions
  4. Junit 5 Platform Launcher API
  5. Creating custom exceptions in Java
  6. Parameterized Tests using JUnit 5
  7. Writing a simple Junit 5 test



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info