Taking a Screenshot in Selenium WebDriver (Java)

With Selenium WebDriver it is possible to take a screenshot when, for example, a test fails. In the code below, we have modified the first test in “BingTests.java” from Page Model using Selenium WebDriver and JUnit so that a screenshot will be taken and saved as a .png in the folder “C:\Selenium\Screenshots” if the test fails. The name of the .png is the date and time of when the screenshot was taken. When run the first test will fail as we are now looking for the link “seleniumhq.org” on the search results page for “Unicycling”.

package com.mycompany.pagemodeldemo;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
 
public class BingTests {
      private static WebDriver driver;   
     
      @BeforeClass   
      public static void setUpBeforeClass() throws Exception {
            File file = new File("C:\\Selenium\\IEDriverServer.exe");      
            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
            driver = new InternetExplorerDriver();    
      }    
     
      @AfterClass   
      public static void tearDownAfterClass() throws Exception {
            driver.quit();       
            driver = null;   
      }    
     
      @Test   
      public void bingSearchForSeleniumHq() { 
            BingHomePage bingHomePage = new BingHomePage(driver);  
            bingHomePage.goToSite();              
            BingSearchResultsPage bingSearchResultsPage = bingHomePage.searchFor("Unicycling");   
            WebElement searchResult = bingSearchResultsPage.findSearchResultByLink("seleniumhq.org");       
            if (searchResult == null) {              
                  try {                  
                        File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                        DateFormat dateFormat = new SimpleDateFormat("HH_mm_ssa yyyy-MM-dd");
                        Calendar cal = Calendar.getInstance();
                        FileUtils.copyFile(screenshotFile, new File("C:\\Selenium\\Screenshots\\"+dateFormat.format(cal.getTime())+".png"));                  
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
                  fail("Search result not found");  
            }   
      }       
     
      @Test   
      public void bingSearchForIEDriver() {   
            BingHomePage bingHomePage = new BingHomePage(driver);   
            bingHomePage.goToSite();            
            BingSearchResultsPage bingSearchResultsPage = bingHomePage.searchFor("Internet Explorer Driver"); 
            WebElement searchResult = bingSearchResultsPage.findSearchResultByLinkText("Internet Explorer Driver - Google Code");    
            if (searchResult == null) {      
                  fail("Search result not found");    
            }  
      }
}

Page Model using Selenium WebDriver and JUnit

The page model for structuring tests represents each webpage in the website under test as a class. Actions are performed on a webpage by calling the methods in the page’s class. The example below will show how to create a page model for testing a Bing search. There are separate classes for the Bing homepage and the Bing search results page, and also a class for the tests.

1. Create a new Java project called “PageModelDemo” (i.e. File > New > Project > Java Project). Add a package called “com.mycompany.pagemodeldemo″ (i.e. Right-click on the src folder > New > Package).

2. Add the Selenium .jar files and the IEDriverServer as in the post Getting Started with Selenium WebDriver, Eclipse and Java

3. Add a class called “BingHomePage.java” and copy the code below into it.

package com.mycompany.pagemodeldemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class BingHomePage {
	
	private WebDriver driver;
	private static String url = "http://www.bing.com";
	
	public BingHomePage(WebDriver driver) {
		this.driver = driver;
	}
	
	public void goToSite() {
		driver.navigate().to(url);
		WebDriverWait wait = new WebDriverWait(driver, 5);		
		wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("q")));
	}
	
	public WebElement findSearchBox() {
		return driver.findElement(By.name("q"));
	}
	
	public WebElement findSearchButton() {
		return driver.findElement(By.name("go"));
	}
	
	public BingSearchResultsPage searchFor(String searchText) {
		findSearchBox().sendKeys(searchText);
		findSearchButton().click();
		WebDriverWait wait = new WebDriverWait(driver, 5);		
		wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("sb_results")));
		return new BingSearchResultsPage(driver);
	}
}

4. Add a class called “BingSearchResultsPage.java” and copy the code below into it.

package com.mycompany.pagemodeldemo;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class BingSearchResultsPage {
	private WebDriver driver;
	
	public BingSearchResultsPage(WebDriver driver) {
		this.driver = driver;
	}	
	
	public List<WebElement> findAllSearchResults() {		
		List<WebElement> allListItems = driver.findElements(By.xpath("//ul[@class = 'sb_results']/li/div/div/div/h3/a"));
		return allListItems;
	}
	
	public WebElement findSearchResultByLink(String partialHyperlink) {
		List<WebElement> allListItems = findAllSearchResults();
		for (WebElement listItem : allListItems) {
			if (listItem.getAttribute("href").toLowerCase().contains(partialHyperlink.toLowerCase())) {
				return listItem;
			}
		}
		return null;
	}
	
	public WebElement findSearchResultByLinkText(String partialLinkText) {
		List<WebElement> allListItems = findAllSearchResults();
		for (WebElement listItem : allListItems) {
			if (listItem.getText().toLowerCase().contains(partialLinkText.toLowerCase())) {
				return listItem;
			}
		}
		return null;
	}
}

5. Add a class called “BingTests.java” and copy the code below into it.

package com.mycompany.pagemodeldemo;

import static org.junit.Assert.*;

import java.io.File;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class BingTests {
	
	private static WebDriver driver;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		File file = new File("C:\\Selenium\\IEDriverServer.exe");
    	System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    	driver = new InternetExplorerDriver();  
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		driver.quit();
		driver = null;
	}

	@Test
	public void bingSearchForSeleniumHq() {
		BingHomePage bingHomePage = new BingHomePage(driver);
		bingHomePage.goToSite();		
		BingSearchResultsPage bingSearchResultsPage = bingHomePage.searchFor("Web Browser Automation");
		WebElement searchResult = bingSearchResultsPage.findSearchResultByLink("seleniumhq.org");	
		if (searchResult == null) {
			fail("Search result not found");
		}
	}
	
	@Test
	public void bingSearchForIEDriver() {
		BingHomePage bingHomePage = new BingHomePage(driver);
		bingHomePage.goToSite();		
		BingSearchResultsPage bingSearchResultsPage = bingHomePage.searchFor("Internet Explorer Driver");
		WebElement searchResult = bingSearchResultsPage.findSearchResultByLinkText("Internet Explorer Driver - Google Code");	
		if (searchResult == null) {
			fail("Search result not found");
		}
	}
}

Note that using the 64 bit version of IEDriverServer with IE 10 can result in the test executing very slowly. In this case switch to the 32 bit version of IEDriverServer as explained on stackoverflow WebDriver and IE10 very slow input.

References
Page-Object pattern for creating a Test Automation Framework
Test Automation Framework in Page-Object pattern using C#, Selenium, SpecFlow and NUnit
Introducing the page class (watin.org)

Selenium WebDriver and JUnit Example

The following program opens a browser window, goes to bing.com, searches for the phrase “Selenium” and then tests that the results page contains a link to SeleniumHQ. You might like to compare this program to the C# version:
Getting Started with Selenium WebDriver and NUnit
or to a version using WatiN rather than Selenium:
Getting Started with WatiN (Part 2)

1. Create a new Java project called “SeleniumDemo2” (i.e. File > New > Project > Java Project). Add a package called “com.mycompany.seleniumdemo2” (i.e. Right-click on the src folder > New > Package).
2. Add a JUnit test case called “SeleniumDemo2” (i.e. Right-click on the package > New > JUnit Test Case). Select the “New JUnit 4 test” radio button and tick the boxes for the “setup()” and “tearDown()” method stubs. When asked to add JUnit 4 to the build path, select Ok.
3. Add the Selenium .jar files and the IEDriverServer as in the post Getting Started with Selenium WebDriver, Eclipse and Java
4. Copy the code below into the class “SeleniumDemo2.java”:

package com.mycompany.seleniumdemo2;

import static org.junit.Assert.*;

import java.io.File;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class SeleniumDemo2 {
	
	private WebDriver driver;

	@Before
	public void setUp() throws Exception {
		File file = new File("C:\\Selenium\\IEDriverServer.exe");
    	System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    	driver = new InternetExplorerDriver();		
        driver.navigate().to("http://www.bing.com");
	}

	@After
	public void tearDown() throws Exception {
		driver.quit();
		driver = null;
	}

	@Test
	public void bingSearchForWatiN()
    {
		driver.findElement(By.name("q")).sendKeys("Selenium");
    	driver.findElement(By.name("go")).click();
    	
        assertEquals(driver.findElement(By.partialLinkText("Selenium - Welcome to nginx!")).getAttribute("href"), "http://seleniumhq.org/");
    }
}

Note that if you find the test fails, the link text may have changed:
Search results

Getting started with Selenium WebDriver, Eclipse and Java

1. Install the Java JDK if it is not already on your machine. The 32-bit (x86) and 64-bit (x64) Windows executables can be downloaded from:
http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Install the Eclipse IDE for Java EE Developers. The .zip (currently “eclipse-jee-kepler-R-win32.zip”) can be downloaded from
http://www.eclipse.org/downloads/
Unzip the file to your chosen destination. For example, if you unzip to “C:\” a folder called “eclipse” will be created there. Double-click on “eclipse.exe” in the “C:\eclipse” folder to start Eclipse. No installation is required.

3. Within Eclipse create a new project called “SeleniumDemo1” (i.e. File > New > Project > Java Project). Add a package called “com.mycompany.seleniumdemo1” (i.e. Right-click on the src folder > New > Package). Add a class called “SeleniumDemo1” (i.e. Right-click on the package > New > Class).

4. Download the Selenium WebDriver Java bindings (currently “selenium-java-2.33.0.zip”) from
https://code.google.com/p/selenium/downloads/list
Unzip the file to your chosen destination, for example, “C:\Selenium”. Within Eclipse right-click on your project > Build Path > Configure Build Path > Libraries tab > Add External JARs > navigate to the folder “C:\Selenium\selenium-2.33.0\selenium-2.33.0\selenium-2.33.0” and add all the .jar files inside and outside the libs folder.

5a. If you want to use Internet Explorer for your tests, then download the 32-bit or 64-bit version of the IEDriverServer (currently “IEDriverServer_Win32_2.33.0.zip” and “IEDriverServer_x64_2.33.0.zip”) from
https://code.google.com/p/selenium/downloads/list
Unzip the file to your chosen destination, for example, “C:\Selenium”.

5b. If you want to use Chrome for your tests, then download the Chrome driver (currently “chromedriver_win32_2.1.zip” for Windows) from
https://code.google.com/p/chromedriver/downloads/list
Unzip the file to your chosen destination, for example, “C:\Selenium”.

6. Copy the code below into the class “SeleniumDemo1.java”:

package com.mycompany.seleniumdemo1;

import java.io.File;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class SeleniumDemo1 {

	public static void main(String[] args) {
	    bingSearchForSeleniumInFirefox();	    
	    bingSearchForSeleniumInIE();
	    bingSearchForSeleniumInChrome();
    }

    public static void bingSearchForSeleniumInFirefox()
    {
    	WebDriver driver = new FirefoxDriver();
    	driver.navigate().to("http://www.bing.com");
    	driver.findElement(By.name("q")).sendKeys("Selenium");
    	driver.findElement(By.name("go")).click(); 
    	try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	driver.quit();
    }
    
    public static void bingSearchForSeleniumInIE()
    {
    	File file = new File("C:\\Selenium\\IEDriverServer.exe");
    	System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    	WebDriver driver = new InternetExplorerDriver();
    	driver.navigate().to("http://www.bing.com");
    	driver.findElement(By.name("q")).sendKeys("Selenium");
    	driver.findElement(By.name("go")).click(); 
    	try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	driver.quit();
    }
    
    public static void bingSearchForSeleniumInChrome()
    {
    	File file = new File("C:\\Selenium\\chromedriver.exe");
    	System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    	WebDriver driver = new ChromeDriver();
    	driver.navigate().to("http://www.bing.com");
    	driver.findElement(By.name("q")).sendKeys("Selenium");
    	driver.findElement(By.name("go")).click(); 
    	try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	driver.quit();
    }
}

When run, this program will complete a Bing search for the word “Selenium” in a Firefox browser, an Internet Explorer browser, and a Chrome browser. Depending on what browsers are installed on your machine, you might want to comment out some of the method calls in the main method. Note that in order for the Internet Explorer test to run you may have to tick or untick “Enable protected mode” in internet options for all four zones “Internet”, “Local intranet”, “Trusted sites” and “Restricted sites”.