When we execute huge number of test scripts, and if some test fails, we need to check why the test has failed. So, its very important to take screenshot when we execute a test script.
Advantage of taking screenshot in Selenium test script :-
- It helps us to debug and identify the problem by seeing the screen shot.
- Save Time
- We can attach same image in Extent report which actually make my reporting better.
Selenium has provided TakesScreenShot interface in this interface you can use getScreenshotAs method which will capture the entire screenshot in form of file then using FileUtils we can copy screenshots from one location to another location.
Capture Screenshot in Selenium Webdriver :
1.File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
2.String screenshotBase64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
getScreenshotAs()
This method is used to capture the screenshot and store it in the specified location. For WebDriver extending TakesScreenshot, this makes a best effort depending on the browser to return the following in order of preference:
- Entire page
- Current window
- Visible portion of the current frame
- The screenshot of the entire display containing the browser
OutputType
getScreenshotAs() method takes OutputType.FILE as parameter. OutputType is an interface in selenium webdriver API. OutputType defines the output type for a screenshot. We can store screenshot in three form
1. BASE64 - Obtain the screenshot as base64 data.
Ex :-
String screenshotBase64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
2. BYTES - Obtain the screenshot as raw bytes.
Ex.
3. FILE - Obtain the screenshot into a temporary file that will be deleted once the JVM exits.
Ex :-
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
The below example explains how to take the screen shot when the test fails.
@Test
public void TakeScreenshot()
{
// Open Firefox
WebDriver driver=new FirefoxDriver();
public void TakeScreenshot()
{
// Open Firefox
WebDriver driver=new FirefoxDriver();
// Maximize the window
driver.manage().window().maximize();
driver.manage().window().maximize();
// Pass the url
driver.get("http://www.google.com");
driver.get("http://www.google.com");
// Take screenshot and store as a file format
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("C:/selenium/Screenshot1.png"));
}
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("C:/selenium/Screenshot1.png"));
}
catch (IOException e)
{
System.out.println(e.getMessage());
{
System.out.println(e.getMessage());
}
}
}
Comments
Post a Comment