Search code examples
javaannotationstestng

How to use custom class annotation in testng listener java


I created a method level java custom annotation like below

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {

    public String id() default "0";
}

Test Class:

public class test {

    @Test
    @Test(id = "231")
    public void test_section(){
        Assert.assertTrue(false);
    }   
}

i was able to use the value of id using below code line

result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class).id();

Now i want to create a class level custom java annotation as below

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface section {

    public String Name() default "0";   
}

and use the same annotation in my test class and get the value of Name in the testng listener ITestListener onTestStart method as i am using testng to execute the test case, below is the test class

@section(Name="u_id")
public class testcustom {

    @Test
    public void test_section(){
        Assert.assertTrue(false);
    }   
}

I am unable to get the value of section, How to get the value of name in section annotation used on class level?


Solution

  • Just looking at the API, something like

    void onTestStart(ITestResult result) {
      section annotation = result.getTestClass().getRealClass().getAnnotation(section.class);
      if (annotation != null) {
        // do something with annotation.Name()
      }
    }
    

    should work (note that Java naming conventions mean it should be Section and name() instead).