During the execution of UI automation tests, when the inspection fails, you often find that the printed log does not effectively help us locate the problem. We need screenshots of the moment of failure to reproduce the failure scene at that time and then troubleshoot the cause of the error.
Based on this requirement, Selenium's screenshot function can be used.
The implementation code is as follows:
import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.time.DateUtils;import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;import org.openqa.selenium.WebDriver;import org.openqa.selenium.interactions.Actions;public static void takeScreeshot(String screenPath, WebDriver chrome){ try { //Specify OutputType.FILE as a parameter to the getScreenshotAs() method, which means returning the screen as a file. File scrFile = ((TakesScreenshot) chrome) .getScreenshotAs(OutputType.FILE); // Key code, execute screenshots, by default, save the screenshot to the temp directory FileUtils.copyFile(scrFile, new File(screenPath)); //Use the copyFile() method of the FileUtils tool class to save the file object returned by getScreenshotAs(). } catch (IOException e) { System.out.println("Screen shot error: " + screenPath); System.out.println("This error can be viewed in the screenshot: "+screenPath); } catch (Exception e) { // TODO: handle exception } } public static void takeScreenshot(WebDriver chrome,String imgName) { String screenName=imgName+DateUtils.MILLIS_PER_DAY+".jpg"; String fileString= "D://selenium//SchoolpalERP_QTP//image"; if (!(new File(fileString).isDirectory())) { // Determine whether the directory exists new File(fileString).mkdir(); // If it does not exist, create a new directory} File dir = new File(fileString); if (!dir.exists()) dir.mkdirs(); String screenPath = dir.getAbsolutePath() + "//" + screenName; takeScreeshot(screenPath, chrome); }The above example code for the screenshot function of Selenium's UI automation test is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.