Tuesday, 8 October 2013

how to take screen shot whenever there is a failure in the framework or test cases in selenium script ?

Our aim is to take screen shot whenever test case fail.There are several way to take screen shots.
1) By putting try  catch - exception code in your framework whenever control comes to catch exception  then take a screen shot by screen shot take method.

2)  By putting listners
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
}

}

3) By writing After Method

@AfterMethod(alwaysRun = true, description = "take screenshot")
public void afterMethod_takeScreenshot(ITestResult result, Method m) throws Exception {
if (!result.isSuccess()) {
TakesScreenshot screen = (TakesScreenshot) driver;
File fileScreen = screen.getScreenshotAs(OutputType.FILE);
File fileTarget = new File("failure_" + m.getName() + ".png");
FileUtils.forceMkdir(fileTarget.getParentFile());
FileUtils.copyFile(fileScreen, fileTarget);
}
}

4)TestWatcher rule
http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatcher.html#!

No comments:

Post a Comment