Method-Level @Tag Example

Java




import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
  
public class MathTest {
  
    @Test
    @Tag("addition")
    void testAddition() {
        System.out.println("Executing test testAddition");
    }
  
    @Test
    @Tag("subtraction")
    void testSubtraction() {
        System.out.println("Executing test testSubtraction");
    }
}


Here we have created another class that is MathTest, in that class we have created two methods for those classes we have created addition and subtraction tags by using @Tag annotation.

JUnit 5 – @Tag

The JUnit 5 testing framework provides a lot of features for testing the application. In those features, Tagging is one of them. This tagging is created using @Tag Annotation JUnit 5. JUnit 5 @Tag is used for filtering the test cases based on the given criteria like characteristics, purpose, and features. @Tag is working like a label in the Test Suite. This @Tag Annotation is used in two different levels. The first one is class level and the other one is method level. This means we can apply this Annotation for both test methods and test classes in the test suite of an application.

  • @Tag with class level
  • @Tag with method level

Syntax for Test class

@Tag("classTag")
public class MyTestClass {
@Test @Tag("methodTag") void testMethod()
{
// Test logic
}
}

Syntax for Test method

public class MyTestClass {
@Test @Tag("methodTag") void testMethod()
{
// Test logic here
}
}

Now we will discuss both of them with examples.

Similar Reads

Class-Level @Tag Example

Java import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test;    @Tag("classTag") public class MyTest {        @Test     @Tag("unitTest")     void exampleOne() {         System.out.println("Executing unit test @Tag");     }        @Test     @Tag("integrationTest")     void exampleTwo() {         System.out.println("Executing integration test @Tag");     } }...

Method-Level @Tag Example

...

Advantages of JUnit 5 – @Tag

Java import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test;    public class MathTest {        @Test     @Tag("addition")     void testAddition() {         System.out.println("Executing test testAddition");     }        @Test     @Tag("subtraction")     void testSubtraction() {         System.out.println("Executing test testSubtraction");     } }...

Conclusion

...

Contact Us