1. Overview

When working with automated tests using Selenium, we often need to take a screenshot of a web page or part of a web page. This can be useful, particularly when debugging test failures or verifying our application behavior is consistent across different browsers.

In this quick tutorial, **we’ll take a look at a couple of ways we can capture screenshots using Selenium WebDriver from our **JUnit tests. To learn more about testing with Selenium, check out our great guide to Selenium.

2. Dependencies and Configuration

Let’s start by adding the Selenium dependency to our pom.xml:

<dependency>

    <groupId>org.seleniumhq.selenium</groupId>

    <artifactId>selenium-java</artifactId>

    <version>3.141.59</version>

</dependency>

As always, the latest version of this artifact can be found in Maven Central.

Now let’s configure our driver to use Chrome from our unit test:


private static ChromeDriver driver;

@BeforeClass

public static void setUp() {

    System.setProperty("webdriver.chrome.driver", resolveResourcePath("chromedriver.mac"));

    Capabilities capabilities = DesiredCapabilities.chrome();

    driver = new ChromeDriver(capabilities);

    driver.manage()

      .timeouts()

      .implicitlyWait(5, TimeUnit.SECONDS);

    driver.get("http://www.google.com/");

As we can see, this is a pretty standard Selenium configuration for a _ChromeDriver _which will let us control the Chrome browser running on our local machine. We also configure the amount of time the driver should wait when searching for an element on the page to five seconds.

Finally, before any of our tests run, we open a favorite web page, www.google.com in the current browser window.

#testing #selenium webdriver

Taking Screenshots With Selenium WebDriver
1.40 GEEK