2

I do some cleanup in external systems using testng @AfterClass annotation. But when tests are failed I really need that data. Can I make testng perform some actions if only tests are passed?

Mikhail Golubtsov
  • 6,285
  • 3
  • 29
  • 36

3 Answers3

4

There is an option to get information about all failed tests till current moment. You have to inject ITestContext into your "afterClass" method.

@AfterClass
public void after(ITestContext context) {
    context.getFailedTests().getAllResults()
}

Iterate through all results and filter by TestClass

Nechaev Sergey
  • 136
  • 1
  • 2
1

AFAIK there is nothing at afterclass/aftersuite level. What you can do is couple of things:

  1. AfterMethod does take ITestResult as an argument which gives you the result of the currently executed test. Based on that you can cleanup.

Or

  1. ISuiteListener gives you an onFinish method with the testresult object, which you can iterate and then do the cleanup.
niharika_neo
  • 8,441
  • 1
  • 19
  • 31
0

Example, where you can delete test data just for current test class if only tests are passed:

@AfterClass
public void deleteCreatedData(ITestContext context) {
    if (hasClassFailedTests(context)) return;
    //do your cleanup for current test class
}

protected boolean hasClassFailedTests(ITestContext context) {
    Class clazz = this.getClass();
    return context.getFailedTests().getAllMethods().stream().anyMatch(it -> 
   it.getRealClass().equals(clazz));
}
Yaryna
  • 340
  • 1
  • 5
  • 11