简体   繁体   中英

How do I catch exceptions if thrown in @BeforeMethod or @BeforeClass without using a TestNGListener

I have a test class each for a specific functionality and have layers of Test Classes that are considered as BaseClass wherein the driver initialization and test kickoff happens (I avoided using Listener here). Defined an AfterMethod in BaseClass which logs out and also captures the results with the exceptions and stacktrace and logs to a database, if the test fails I am able to capture the exceptions, the exceptions are not caught if the BeforeMethod or BeforeClass fails, all I see is test status which is shown as SKIPPED. Here is the piece of code that I use in AfterMethod:

public void afterMethodBase(ITestResult result) { 
        logger.debug("TestName : " + result.getTestName());
        logger.info("Method Name : " + result.getMethod().getMethodName());
        ResultLogger.processResult(result);
        Throwable exception = itr.getThrowable(); // this is null when status is skipped
}

How to catch the exceptions raised in BeforeMethod or BeforeClass

You can use a listener with its appropriate method: IConfigurationListener#onConfigurationFailure(ITestResult)

Check the documentation for more details about listeners.

If accessing it via the Listeners is not something that you want to do, then why not access them like this ?

From the ITestResult object that get through your @AfterMethod annotated method:

  • First get hold of all the failed configuration methods via result.getTestContext().getFailedConfigurations().getAllMethods()

  • Then you iterate through the above collection of ITestNGMethod to filter out only @BeforeClass failures by calling org.testng.ITestNGMethod#isBeforeClassConfiguration

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