Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanup after each test method in testng framework

I have 100 test methods. After each test, I need to perform some actions (data cleanup). Each of these 100 tests have different actions. These 100 test are not in one package or class. They are distributed.

How can I achieve this?

Right now, if a test passes, the cleanup happens, since it is part of the test. However, if the test fails, the cleanup doesn't happen. How can I make this work?

Any pointers would help.

like image 482
kavita Avatar asked Mar 30 '26 03:03

kavita


2 Answers

If the tests do not have any common cleanup, you can ensure the test gets cleaned up from within the test method using a try/finally block, something like:

try {
   // do test
}
finally {
   // do cleanup
}

If there is any common cleanup between the test methods you could use @AfterMethod to do the cleaup.

In your case, it doesn't sound like there is much common cleanup, so the first may work better for you. It might also be worth considering if you need 100 different cleanup methods or if there can be any common setup/cleanup.

like image 192
Jeff Storey Avatar answered Apr 02 '26 02:04

Jeff Storey


@AfterMethod would mean that you would need that every class gets this method. So you would need to go and edit each class/method. Same for @AfterGroups.

What I would suggest is to implement the IInvokedMethodListener. This would give you beforeInvocation and afterInvocation methods. In the afterInvocation method, implement your cleanup code. Create a suite file with all of your tests which need this cleanup and specify this listener.

Hope it helps.

like image 38
niharika_neo Avatar answered Apr 02 '26 02:04

niharika_neo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!