Selenium(Java) Hack you MUST know as an Test Automation Engineer! P.2

Davit Danelia
2 min readMar 18, 2021

--

(Catch failed Test Cases with screenshot)

While doing automated testing, we almost always have the machine in front of us to check what happened or when the test case failed, but what if we have many parrallel tests or we missed some failed tests because of human factor… you must re-run tests or search in console logs for understanding the failure, and that’s ok, but…

If the test case fails, a safer approach is to take a snapshot of the website. With the help of the screenshot, we were able to pinpoint precisely where the script had crashed.

To accomplish this, we should wrap the whole code (shown below) in a try-catch block. That is, placed the test steps in the try block and the screen capture statement in the catch block. If a test step fails in the try block, the code proceeds to the catch block, where it captures a snapshot of the web page in the browser and determines whether the test failed.

Another way of capturing screenshot of failed tests using Selenium WebDriver is to use ITestResult.getStatus(), ITestResult.getStatus() provides us test result of executed test case, for example when test fails ITestResult.getStatus() function gives output 2 That means that execution of this test Failed

Best use of ITestResult.getStatus() is to use it with for example: AfterMethod annotation then this particular method (AfterMethod) executes after every test execution.

Below is a script that demonstrates how to take a screenshot using ITestResult Interface with TestNG AfterMethod.

That’s all, now you can use this screen shot taking function whenever you want, will be it when your test cases fails or in some specific situation!

Enjoy, Subscribe And Clap!

Peace ✌️

--

--