Search code examples
javaannotationsextentreports

Java Test Automation - Test Case Annotation to Extent report


I created a new annotation

@Target(ElementType.METHOD)
public @interface DisplayName {
    String value() ; 
}

That I wanted to use in order to define the test case name in extent report. On test case:

@Test
@DisplayName("testcase title")
public void TestCase_1() throws InterruptedException {...}

In The TestListener I now managed to set the title of the test case using the description field.

    @Override
public void onTestStart(ITestResult iTestResult) {
    System.out.println("I am in onTestStart method " + getTestMethodName(iTestResult) + " start");
    // Start operation for extentreports.
    ExtentTestManager.startTest(iTestResult.getMethod().getDescription(), iTestResult.getMethod().getDescription());
}

I would like to use the @DisplayName annotation as test case title but I don't know how to bring the annotation value in TestListener.

Thanks in advance!

SOLUTION__________________With great help from @Kovacic__________________SOLUTION

Final Result:

Annotation class:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DisplayName {
    String value();
}

TestListener Class:

........
@Override
    public void onTestStart(ITestResult iTestResult) {

        String valueFromInterface = null;

        Method method = iTestResult.getMethod().getConstructorOrMethod().getMethod();

        if (method.isAnnotationPresent(DisplayName.class)) {
            DisplayName displayName = method.getAnnotation(DisplayName.class);
            if (displayName != null) {
              valueFromInterface = displayName.value();
            }
        }

        ExtentTestManager.startTest(valueFromInterface, iTestResult.getMethod().getDescription());
    }

........

Solution

  • I hope I understood this question, here is solution

    if You use this as interface:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface ITestrail {
        public @interface DisplayName {
            String value() ; 
        }
    

    also You need to add to Your interface (line bellow):

    @Retention(RetentionPolicy.RUNTIME)
    

    try this:

    @Override
    public void onTestStart(ITestResult result) {
    
        String valueFromInterface;
    
        Method method = result.getMethod().getMethod();
    
        if (method.isAnnotationPresent(DisplayName.class)) {
            DisplayName displayName = method.getAnnotation(DisplayName.class);
            if (displayName != null) {
              valueFromInterface = displayName.value();
            }
        }
    
        ExtentTestManager.startTest(iTestResult.getMethod().getDescription(), valueFromInterface);
    }
    

    Hope this helps,