Automation Test Practice

Follow me on GitHub

Take Screenshot Only When a Test Fail

When we conduct GUI test, it is not efficient if we take screenshot on each step, it also will produce lots of unusful screenshot files. However if a test failed, we do want to see the screenshot to facilitate bug investigation. How to make the automation code take screenshot ONLY when the test fail?

Very often I see people to make the failed test case throw a specific exception, then catch the exception and take screenshot. This is really weird and also violiated the JAVA exception usage principle — exception should only be used in exceptioal scenario.

Actually there is a simpe solution. Most often, we use TestNG, and TestNG has an interface named ITestListener. It defines a method onTestFailure(ITestResult result). We can override this method with screenshot taking code inside. This interface has many other methods. If we implement ITestListener directly, we have to implement other methods as well, basically leave them as empty. Fortunatelly TestNG has an addapter named TestListenerAdapter , it implements ITestListener already. Thus we can extends from this addapter.
screen_1.png

To make this ScreenshotListener get effective, don’t forget to put it under your TestNG xml file like following:

<listeners>
    <listener class-name="com.goodluck.automation.helper.ScreenshotListener" />
</listeners>

Happy Automation Test ~~~~~

Back To Homepage