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?
Asked
Active
Viewed 1,725 times
2
-
Can you tell what the real problem is? It seems strange that you want to always delete the data that made your test fail – Raffaele Aug 27 '15 at 05:55
-
No, it's the opposite. I want to delete test data if only it's passed. – Mikhail Golubtsov Aug 27 '15 at 05:57
-
Better. So you should adjust title and description: they say the opposite – Raffaele Aug 27 '15 at 05:58
-
Yep, thank you for pointing out. – Mikhail Golubtsov Aug 27 '15 at 06:02
-
According to the documentation it may be a [bug](https://github.com/cbeust/testng/issues/415) (unconfirmed). [This is an alternative](http://stackoverflow.com/a/18600030/315306) – Raffaele Aug 27 '15 at 06:29
3 Answers
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:
- AfterMethod does take ITestResult as an argument which gives you the result of the currently executed test. Based on that you can cleanup.
Or
- 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