0
votes

I want to test some database-related classes in my application using TestNG framework.

To make it easier I added a test group "database" and made a test class TestUtil, which contains two methods: one with @BeforeGroups(groups = "database") annotation, it's setting up EntityManager and some other resources, and another one marked with @AfterGroups(groups = "database"), which frees up these resources.

Most of my test classes persisting some entities to database during the test, and I want to clean up the DB after all test methods of the class are invoked.

If I use @AfterClass annotation, it runs after the @AfterGroups methods, what is unacceptable for me because clean-up method still needs active EntityManager and other DB-related resources.

I can mark those clean-up methods with @Test(dependsOnMethods = "lastTestMethodInThisClass"), but in this case I'll need to edit this annotation each time I add new test method to the class.

Is there another, more convenient way to do this job?

2

2 Answers

0
votes

No, there is no such annotation which allows you to run code after all @Test and before @AfterGroups. But instead of @Test(dependsOnMethods = "lastTestMethodInThisClass") you can implement org.testng.IMethodInterceptor as listener and change @Test order in org.testng.IMethodInterceptor#intercept - basically search your 'last test' in the list put your 'last test' which handles/closes resources to the end and return modified list. So you don't have to change dependsOnMethods when you add new test because interceptor do it for you.

0
votes

If you want to run a cleanup method after all the tests are invoked, you can write your code in your cleanup method with @AfterSuite annotation. This will be executed after the whole suite has finished execution.