Adept Adept - 2 months ago 35
Java Question

Get current class test methods before class started in TestNG

I would like to get a list of test methods from the current test class before it is started. When I tried to extend TestListenerAdapter for this, testContext.getAllTestMethods() returned all test methods from all classes. But how to get only methods from the current class?

Answer

I found a partial answer on the question. First of all, I can get all test methods by extending TestListenerAdapter

public class MyListener extends TestListenerAdapter {

@Override
public void onStart(ITestContext testContext) {
    super.onStart(testContext);
    ITestNGMethod[] methods = testContext.getAllTestMethods();
    // here we can save methods into some object
}

Then, in our test class in @BeforeClass() we can access the object and get the only methods from the this.getClass().getName() class. So, we filter the only methods from the current class. In this case we can access all required information like description and other important test attributes.