TestNG - @BeforeMethod for specific methods

java, spring, spring-test, testng

Solution

You could add a parameter your @BeforeMethod with the type 'java.lang.reflect.Method'. TestNG will then inject the reflection information for the current test method including the method name, which you could use for switching.

If you add another 'Object' parameter, you will also get the invocation parameters of the test method.

You'all find all on possible parameters for TestNG-annotated methods in chapter 5.18.1 of the TestNG documentation.

Problem

I'm using Spring Test with TestNG to test our DAOs, and I wanted to run a specific text fixture script before certain methods, allowing the modifications to be rolled back after every method so that the tests are free to do anything with the fixture data. Initially I thought that 'groups' would be fit for it, but I already realized they're not intended for that (see this question: TestNG BeforeMethod with groups ). Is there any way to configure a `@BeforeMethod` method to run only before specific `@Test`s? The only ways I see are workarounds: - Define an ordinary setup method and call at the beginning of every `@Test` method; - Move the `@BeforeMethod` method to a new class (top level or inner class), along with all methods that depend on it. Neither is ideal, I'd like to keep my tests naturally grouped and clean, not split due to lack of alternatives.

Original source

Related problems