Taking ScreenShot ONLY for Failed Tests

We have discussed about simple way of taking a screen shot earlier. Now in this tutorial, we will see how to take screen shot ONLY for failed tests.

To do this, first we need to create a class and then implement TestNG ‘ITestListener’. We will have a method called ‘onTestFailure’. We need to add the code to take the screen shot in this method. Instead of just taking the screen shot, we will get the Test method name and take a screen shot with test name and place it is destination folder.

package com.pack.listeners;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import com.pack.sample.TestBase;

public class TestListener implements ITestListener {
WebDriver driver=null;
String filePath = “D:\\SCREENSHOTS”;
@Override
public void onTestFailure(ITestResult result) {
System.out.println(“***** Error “+result.getName()+” test has failed *****”);
String methodName=result.getName().toString().trim();
takeScreenShot(methodName);
}

public void takeScreenShot(String methodName) {
//get the driver
driver=TestBase.getDriver();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with test method name
try {
FileUtils.copyFile(scrFile, new File(filePath+methodName+”.png”));
System.out.println(“***Placed screen shot in “+filePath+” ***”);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onFinish(ITestContext context) {}

public void onTestStart(ITestResult result) { }

public void onTestSuccess(ITestResult result) { }

public void onTestSkipped(ITestResult result) { }

public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }

public void onStart(ITestContext context) { }
}
Before executing the above program, we need to add TestListener class in testng.xml file as below:

<listeners>
<listener class-name=”com.pack.listeners.TestListener”/>
</listeners>
In the Next tutorial, we will try to extend the way of taking the screen shot and placing it by creating a folder with Test Class name and Screens shots of that particular test class as shown in below screen shot. Click here for example on Take Screenshot and place it in a folder with Test Class name

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s