Mikhail Golubtsov
Mikhail Golubtsov

Reputation: 6653

@AfterClass/Suite in testng if only tests were passed

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?

Upvotes: 2

Views: 1960

Answers (3)

Yaryna
Yaryna

Reputation: 370

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));
}

Upvotes: 0

Nechaev Sergey
Nechaev Sergey

Reputation: 136

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

Upvotes: 4

niharika_neo
niharika_neo

Reputation: 8531

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.

Upvotes: 1

Related Questions