Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve Class level Tags?

I am trying to retrieve class tags only. In the below case, I want to handle This is my sample test using java junit5. I don’t want to use TestInfo. Is there another solution I can use while retrieving Tag info associated with the class

@Tag("This is my sample test")
public class TestSample {

  @Tags(value = {@Tag("Test1"), @Tag("Test2"), @Tag("Test3")})   
  public void method1()


  @Tags(value = {@Tag("Test1"), @Tag("Test2"), @Tag("Test3")})   
  public void method2()
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The retention policy of Junit 5 Tag is: @Retention(RetentionPolicy.RUNTIME)

https://github.com/junit-team/junit5/blob/main/junit-jupiter-api/src/main/java/org/junit/jupiter/api/Tag.java

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Repeatable(Tags.class)
@API(status = STABLE, since = "5.0")
public @interface Tag {

Therefore it could be as simple as using Reflection to retrieve it:

import org.junit.Test;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Tags;

import java.util.stream.Stream;


@Tag("This is my sample test")
public class ExampleTagTest {

    @Tags(value = {@Tag("Test1"), @Tag("Test2"), @Tag("Test3")})
    @Test
    public void method1() {

        Class thisClass = ExampleTagTest.class;

        Stream.of(thisClass.getAnnotations()).forEach(annotation -> {

            if(annotation instanceof Tag){
                System.out.println(((Tag)annotation).value());
            }

        });
    }

    @Tags(value = {@Tag("Test1"), @Tag("Test2"), @Tag("Test3")})
    @Test
    public void method2() {

    }
}

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading