You can use below function to capture screenshot.
/**
* This function is used to capture screenshot and store it in directory
* @param driver -Pass your WebDriver instance.
* @param screenshotdir - Pass your screenshot directory
* @return - Returns location where screenshot is stored.
* @throws IOException
*/
public static String captureScreenshot(WebDriver driver,
String screenshotdir) throws IOException {
String randomUUID = UUID.randomUUID().toString();
String storeFileName = screenshotdir + "\\"
+ getFileNameFromURL(driver.getCurrentUrl()) + "_"
+ randomUUID + ".png";
String[] screenshotdirsplit = screenshotdir.split("\\\\");
String fileName = screenshotdirsplit[screenshotdirsplit.length - 1] + "\\"
+ getFileNameFromURL(driver.getCurrentUrl()) + "_"
+ randomUUID + ".png";
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(storeFileName));
return fileName;
}
In above function, I am accepting WebDriver object and screenshot directory. I generate random UUID so that my image file name can be unique all the time. I take screenshot and store it in a file and return the File name.
Hope that helps!