Take screeenshot will take images when any method is fail or execution stop some how, let example in automation we user assert to verify values when there is some changes in application then assert is fail and it throw some exception so in exception if we add takescreenshot("Parameter name") method then it will take sscreen shot of fail page.
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;
public class elementdetials {
/**If this method Fail then screen show take and stored in folder**/
public void onTestFailure(ITestResult result) {
WebDriver driver = new FirefoxDriver();
driver.get("https://qamanual.blogspot.com");
driver.manage().window().maximize();
WebElement headerelement = driver.findElement(By.linkText("HOME"));
try{
Assert.assertEquals("Home",headerelement.getText());
}
catch (IOException e) {
e.printStackTrace();
takeScreenShot(methodName);
}
}
public void takeScreenShot(String methodName) {
String filePath= "user.dir";
File scrFile = ((TakesScreenshot)webDriver).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+"\\Screenshot\\" + methodName+".png"));
System.out.println("***Placed screen shot in "+filePath+" ***");
} catch (IOException e) {
e.printStackTrace();
}
}
}
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;
public class elementdetials {
/**If this method Fail then screen show take and stored in folder**/
public void onTestFailure(ITestResult result) {
WebDriver driver = new FirefoxDriver();
driver.get("https://qamanual.blogspot.com");
driver.manage().window().maximize();
WebElement headerelement = driver.findElement(By.linkText("HOME"));
try{
Assert.assertEquals("Home",headerelement.getText());
}
catch (IOException e) {
e.printStackTrace();
takeScreenShot(methodName);
}
}
public void takeScreenShot(String methodName) {
String filePath= "user.dir";
File scrFile = ((TakesScreenshot)webDriver).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+"\\Screenshot\\" + methodName+".png"));
System.out.println("***Placed screen shot in "+filePath+" ***");
} catch (IOException e) {
e.printStackTrace();
}
}
}