Capture Screenshot on Test Failure & Success Using Appium and TestNG

Detect Bug 🐛 using the screenshot

Fareena Imran
3 min readFeb 23, 2022

If you need step by step solution for implementation then jump at this topic. Let’s get started 👇

First, download and install the “ApiDemos-debug.apk” app on which we will run our test case and will capture a screenshot of test failure and success. Now inspect this app using UIAutomatorViewer 👇

Scenario 💭

Now let’s discuss the scenario. We’re actually going to create two test cases one will be failed (intentionally) to get the screenshot on failure and the other will be successful to get the screenshot on test success.

Test Cases:

◾️ TestForSuccess: Our test is to check if the text given in assert matches with screen name appears when selecting an item from the list.

Steps: Select “Text” → “Linkify” → Open the screen with the name “Text/Linkify”.

◾️ TestForFailure: Our test is to check if the text given in assert matches with screen name appears when selecting an item from the list. but i intentionally give wrong ❌ value in assert to make the test fail 😜.

Steps: Select “Text” → “Unicode” → Open the screen with the name “Text/Unicode”.

Capture Screenshot

To capture the screenshot on test failure and success, you need to create a java class with listener interface (you can read my previous article to create this class).

◾️ CaptureScreenshot Method

In Java Class that implements listener interface, here is a method to cature screenshot.

◾️ OnTestSuceess & OnTestFailure methods

Also, you need to call the “captureScreenshot” method in these to methods to perform action according to status of execution. If test case got failed ❌ or success ✔️ the result will be captured in “tr” object.

◾️ XML File

You need to give <listeners> tag in XML so that the listener will keep listening 👂 for test failure or success and will active the methods in listener class to perform particular action.

You need to run the XML file to see the results 💻

◾️ Sceendshots folder

When you will execute the XML file, will get a “screenshots” folder in project like 👇

If you don't get a folder after execute of XML file. Go to project → build project. then the folder will be appeared in project directory.

Code for Implementation

If you face any issues feel free to ask in the comments.

If you find this post useful, please tap 👏 button below 😊

Best of Luck 👍

--

--