Thursday, July 1, 2010

TestNG - Take Screenshot of Failed Test Cases.

In my project I required to take to take the screenshot of the failed test cases. I initially searched for ready made listeners that can do this. Bug when i failed to find any i decided to write down my own.

I also wanted the screenshots to be embedded in ReportNG report. But HTML tags in ReportNG report is by default disabled. You require to set its system property to enable to HTML Tags in report.

The following listener will take the screenshot of the failed testcases and will embed that in your ReportNG report but for that you require to change in your TestNG task in your build.xml.

Listener to Take the screenshot of failed testcases
package test.Lib;

import java.io.File;

import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;

public class Screenshot extends TestListenerAdapter {

@Override
public void onTestFailure(ITestResult result) {
File file = new File("");

Reporter.setCurrentTestResult(result);
System.out.println(file.getAbsolutePath());
Reporter.log(file.getAbsolutePath());

Reporter.log("screenshot saved at "+file.getAbsolutePath()+"\\reports\\"+result.getName()+".jpg");
Reporter.log("<a href='../"+result.getName()+".jpg' <img src='../"+result.getName()+".jpg' hight='100' width='100'/> </a>");
BaseClass.selenium.captureScreenshot(file.getAbsolutePath()+"\\reports\\"+result.getName()+".jpg");
Reporter.setCurrentTestResult(null);
}


@Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
}

@Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass 
}

}



BaseClass: BaseClass is the class where my setup(@BeforeClass) and teardown(@AfterClass) method is declared. I have taken selenium object is static so i can access it directly by its classname.

To use this listener you need to mention that in your Testng.xml file as follows.

<suite name="TestNG Take Screenshot of failed Test cases">
<listeners>
<listener class-name="Screenshot" /> 
</listeners>
<test verbose="6" name="Summery and Submit Page Page">
<classes>
<class name=test.Lib.testScreenshot" />
</classes>
</test>
</suite>


Changes Require in TestNG task to enable HTML tags in ReportNG report.
<project name="ScreenShotFailedTestcases" basedir=".">
<target name="TestNG" depends="compile">
<taskdef resource="testngtasks" classpathref="lib.classpath"/>
<testng outputDir="${report.dir}" 
haltonfailure="false"
useDefaultListeners="false"
listeners="org.uncommons.reportng.HTMLReporter"
classpathref="lib.classpath">
<!-- <classfileset dir="${classes.dir}" includes="**/*.class" /> -->
<xmlfileset dir="${basedir}" includes="testng.xml"/>  
<sysproperty key="org.uncommons.reportng.escape-output" value="false"/>
</testng> 
</target>
</project>