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"); } } }