简体   繁体   中英

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.

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.

@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.

It sounds like you may already be using @AfterMethod to cleanup after the tests. To make @AfterMethod work after a failure, you need to use:

@AfterMethod(alwaysRun=true)

You can use groups and run a @AfterGroups somewhere. There's a @BeforeGroups as well. Setting it up with build tooling is a bit tedious and there are some interactions with IDEs as well. There's a BeforeSuite and AfterSuite as well, I believe.

An alternative could be using Spring and using the same spring context in all your tests (spring context gets reused that way). You can then do some things when the context is destroyed after your tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM