Search code examples
automationannotationstestng

Get the name of currently executing @Test method name in @BeforeMethod and @AfterMethod in testng


I want to Print the name of Currently Executing Test Method in @BeforeMethod and @AfterMethod using testng. Like :

public class LoginTest {

@Test
public void Test01_LoginPage(){
    //Some Code here
}


@Test
public void Test02_LoginPage(){
    //Some Code Here
}

@BeforeMethod
public void beforeTestCase(){
    //Print Test method name which is going to execute.
}

@AfterMethod
public void AfterTestCase(){
    //Print Test method name which is executed.
}
}

Solution

  • You can use listeners like this link. Important code from the link:-

    // This belongs to IInvokedMethodListener and will execute before every method including //@Before @After @Test

    public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) {
    
        String textMsg = "About to begin executing following method : " + returnMethodName(arg0.getTestMethod());
    
        Reporter.log(textMsg, true);
    
    }
    
    // This belongs to IInvokedMethodListener and will execute after every method including @Before @After @Test
    
    public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) {
    
        String textMsg = "Completed executing following method : " + returnMethodName(arg0.getTestMethod());
    
        Reporter.log(textMsg, true);
    
    }
    
    // This will return method names to the calling function
    
    private String returnMethodName(ITestNGMethod method) {
    
        return method.getRealClass().getSimpleName() + "." + method.getMethodName();
    
    }