Tuesday 29 April 2014

Selenium Screenshot

package mypackage;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Screenshot {
  
    @Test
    public void takeScreenshot() throws InterruptedException, IOException  {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com.tr");
        driver.manage().window().maximize();
        Thread.sleep(2000);
        driver.findElement(By.id("gbqfq")).sendKeys("onurtest");
        driver.findElement(By.name("btnG")).click();
        Thread.sleep(3000);
        // take the screenshot
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        // now save the screenshot to a file some place
        FileUtils.copyFile(scrFile, new File("h:\\tmp\\screenshot.png"));
        WebElement resultsLabel = driver.findElement(By.id("resultStats"));
        assertEquals(true, resultsLabel.isDisplayed());
        driver.close(); // This will not execute
    }

}