Search code examples
javaannotationsautomated-teststestngtestrail

TestNG BeforeClass and AfterMethod equivalent methods for TestNG listener


Taking the below base class methods testSetup() and getStatusAndAnnotation() and putting them into TestNG Listener. I could find the equivalent of @BeforeClass as onBeforeClass(ITestClass, IMethodInstance). However, what is the equivalent for @AfterMethod?

My aim is to pass the ITestResult as a parameter to that method because I will be holding the test result into it. The code below shows that I am getting the annotation and status of test and then pushing it to the testrail cloud. I tried using:

@Override
    public void afterInvocation(IInvokedMethod, ITestResult) {
        ..
    }

It did not help and gave

java.lang.NoSuchMethodException: client.test.reporting.listeners.TestRailListener.test_getVersion()
    at java.lang.Class.getMethod(Class.java:1670)

Here Java: 1670 is

 throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));

**@BeforeClass
        public static void testSetup() throws InterruptedException, IOException, APIException {
            initTestRail();
        }
@AfterMethod
public void getStatusAndAnnotation(ITestResult result) throws NoSuchMethodException, IOException, APIException {
    HashMap<Object, Object> map = new HashMap<>();
    Method m = getClass().getMethod(result.getName());
    TestCase annotation = m.getAnnotation(TestCase.class);
    try {
        map.put("testRailCaseId",annotation.testRailCaseId());
    }catch (NullPointerException e){}
    if (result.isSuccess()) {
        map.put("result", 1);
    } else {
        map.put("result", 5);
    }
    if(annotation.testRailDeployEnable() && !map.get("testRailCaseId").equals(null) && !map.get("testRailCaseId").toString().isEmpty())
    {
        TestRailIntegration.addTestResult(map);
    }
    else System.out.println("Deploying result was canceled, because test has annotation \"testRailDeployEnable: false\" or \"testRailCaseId\" has no value");
}**

After every method is executed, whatever maybe the status (PASS/FAIL/SKIP), I want to execute this getStatusAndAnnotation...() but it gives above exception/error.


Solution

  • I think you can implement org.testng.ITestListener, but instead of single method afterInvocation() it has several depending on the result: onTestSuccess(), onTestFailure(), onTestSkipped(), etc. Every method is passed ITestResult object, which also contains method being executed:

    @Override public void onTestSuccess(ITestResult iTestResult) { Method method = iTestResult.getMethod().getConstructorOrMethod().getMethod(); Annotation[] annotations = method.getDeclaredAnnotations(); ... }