Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Selenium Testing Tools Cookbook Second Edition
Selenium Testing Tools Cookbook Second Edition

Selenium Testing Tools Cookbook Second Edition: Over 90 recipes to help you build and run automated tests for your web applications with Selenium WebDriver

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Selenium Testing Tools Cookbook Second Edition

Chapter 1. Getting Started

In this chapter, we will see how to set up the Selenium WebDriver test development environment. We will also see some basic settings to help get started with Selenium WebDriver. You will learn the following:

  • Configuring the Selenium WebDriver test development environment for Java with Eclipse and Maven
  • Using Ant for Selenium WebDriver test execution
  • Configuring Microsoft Visual Studio for Selenium WebDriver test development
  • Configuring Selenium WebDriver for Python and Ruby
  • Setting up Internet Explorer Driver Server
  • Setting up ChromeDriver for Google Chrome
  • Setting up Microsoft WebDriver for Microsoft Edge

Introduction

Selenium WebDriver has been widely used for automating web browsers in combination with various tools due to its neat and clean object-oriented design. We can integrate Selenium WebDriver with other tools to develop automated tests.

The initial sections of this chapter explore Selenium WebDriver's integration with development and build tools such as Eclipse, Maven, and Microsoft Visual Studio. These tools provide an easy way to develop test automation frameworks and extend the capabilities of Selenium WebDriver API. The following recipes will explain how to set up and configure these tools with Selenium.

Lastly, we will explore how to set up various browser drivers and initial settings for WebDriver.

Configuring the Selenium WebDriver test development environment for Java with Eclipse and Maven

Selenium WebDriver is a simple API that can help with browser automation. However, much more is needed when using it for testing and building a test framework. You will need an Integrated Development Environment (IDE) or a code editor to create a new Java project and add Selenium WebDriver and other dependencies in order to build a testing framework.

In the Java world, Eclipse is a widely used IDE, as well as IntelliJ IDEA and NetBeans. Eclipse provides a feature-rich environment for Selenium WebDriver test development.

Along with Eclipse, Apache Maven provides support for managing the entire life cycle of a test project. Maven is used to define project structure, dependencies, build, and test management.

You can use Eclipse and Maven to build your Selenium WebDriver test framework from a single window. Another important benefit of using Maven is that you can get all the Selenium library files and their dependencies by configuring the pom.xml file. Maven automatically downloads the necessary files from the repository while building the project.

This recipe will explain how to configure Eclipse and Maven for the Selenium WebDriver test development. Most of the code in this book has been developed in Eclipse and Maven.

Getting ready

You will need Eclipse and Maven to set up the test development environment. Download and set up Maven from http://maven.apache.org/download.html. Follow the instructions on the Maven download page (see the Installation Instructions section on the page).

Download and set up Eclipse IDE for Java Developers from https://eclipse.org/downloads/.

Note

The examples for this book are built in Eclipse version 4.4.2 (codenamed Luna) for Java Developers. This comes with the Maven plugin bundled with other packages.

How to do it...

Let's configure Eclipse with Maven to develop Selenium WebDriver tests using the following steps:

  1. Launch the Eclipse IDE.
  2. Create a new project by selecting File | New | Other from the Eclipse Main Menu.
  3. On the New dialog, select Maven | Maven Project, as shown in the following screenshot, and click Next:
    How to do it...
  4. Next, the New Maven Project dialog will be displayed. Select the Create a simple project (skip archetype selection) checkbox and click on the Next button, as shown in the following screenshot:
    How to do it...
  5. On the New Maven Project dialog box, enter com.secookbook.examples in the Group Id: textbox and SeleniumCookbook in the Artifact Id: textbox. You can also add a name and description optionally. Click on the Finish button, as shown in the following screenshot:
    How to do it...
  6. Eclipse will create the SeleniumCookbook project with a structure (in Package Explorer) similar to the one shown in the following screenshot:
    How to do it...
  7. Select pom.xml from Package Explorer. This will open the pom.xml file in the editor area with the Overview tab open. Select the pom.xml tab next to the Overview tab, as shown in the following screenshot:
    How to do it...
  8. Add the WebDriver and JUnit dependencies highlighted in the following code snippet to pom.xml in the <project> node:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.secookbook.examples</groupId>
      <artifactId>SeleniumCookbook</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <dependencies>
        <dependency>
          <groupId>org.seleniumhq.selenium</groupId>
          <artifactId>selenium-java</artifactId>
          <version>2.47.1</version>
    <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
    <scope>test</scope>
        </dependency>
        </dependencies>
    </project>

    You can get the latest dependency information for Selenium WebDriver and JUnit from http://seleniumhq.org/download/maven.html and http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html respectively.

    Tip

    TestNG is another widely used unit-testing framework in Java World. If you want to add TestNG support to the project instead of JUnit, you can get its Maven entry at http://testng.org/doc/maven.html.

  9. Select src/test/java in Package Explorer and right-click to show the menu. Select New | Class, as shown in the following screenshot:
    How to do it...

    Tip

    Downloading the example code

    You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  10. Enter com.seleniumcookbook.examples.chapter01 in the Package: textbox and GoogleSearchTest in the Name: textbox and click on the Finish button, as shown in the following screenshot:
    How to do it...

    This will create the GoogleSearchTest.java class in the com.secookbook.examples.chapter01 package.

  11. Add the following code in the GoogleSearchTest class:
    package com.secookbook.examples.chapter01;
    
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.By;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.junit.*;
    
    import static org.junit.Assert.*;
    
    public class GoogleSearchTest {
    
      private WebDriver driver;
    
      @Before
      public void setUp() {
        // Launch a new Firefox instance
        driver = new FirefoxDriver();
        // Maximize the browser window
        driver.manage().window().maximize();
        // Navigate to Google
        driver.get("http://www.google.com");
      }
    
      @Test
      public void testGoogleSearch() {
        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));
        // Clear the existing text value
        element.clear();
    
        // Enter something to search for
        element.sendKeys("Selenium testing tools cookbook");
    
        // Now submit the form
        element.submit();
    
        // Google's search is rendered dynamically with JavaScript.
        // wait for the page to load, timeout after 10 seconds
        new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return d.getTitle().toLowerCase()
              .startsWith("selenium testing tools cookbook");
          }
        });
    
        assertEquals("Selenium testing tools cookbook - Google Search",
          driver.getTitle());
      }
    
      @After
      public void tearDown() throws Exception {
        // Close the browser
        driver.quit();
      }
    }

    Tip

    Downloading the example code:

    You can download the example code files for all the Packt books you have purchased from your account at http://www.packtpub.com. If you have purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    The example code is also hosted at https://github.com/upgundecha/secookbook.

  12. To run the tests in the Maven life cycle, select the SeleniumCookbook project in Package Explorer. Right-click on the project name and select Run As | Maven test. Maven will execute all the tests from the project.

How it works...

Eclipse provides the ability to create Selenium WebDriver test projects easily with its Maven plugin, taking away the pain of project configurations, directory structure, dependency management, and so on. It also provides a powerful code editor to write the test code.

When you set up a project using Maven in Eclipse, it creates the pom.xml file, which defines the configuration of the project and its structure. This file also contains the dependencies needed for building, testing, and running the code. For example, the following code shows the dependency information about Selenium WebDriver that we added in pom.xml:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>2.47.1</version>
</dependency>

Most open source projects publish this information on their websites. In this case, you can check http://seleniumhq.org/download/maven.html; you can also get this information from Maven Central at http://search.maven.org/#browse. Maven will automatically download libraries and support files mentioned for all the dependencies and add to the project without you needing to find, download, and install these files to the project. This saves a lot of our time and effort while managing the dependency-related tasks.

Maven also generates a standard directory structure for your code, for easier management and maintenance. In the previous example, it created the src/test/java folder for the test code and the src/test/resources folder to maintain resources needed for testing, such as test data files, utilities, and so on.

Maven provides life cycle steps such as building the test code and running the test. If you are working with the Java development team, then you might find the application code and test code together in Maven. Here, Maven supports building the application code, then firing the tests, and releasing the software to production.

There's more…

Maven can also be used to execute the test from the command line. To run tests from the command line, navigate to the SeleniumCookbook project folder through the command line and type the following command:

mvn clean test

This command will traverse through all the subdirectories and run the clean command to delete/remove earlier build files. It will then build the project and run the tests. You will see the results at the end of execution on command line, as shown in the following screenshot:

There's more…

Using Ant for the Selenium WebDriver test execution

Apache Ant is a popular build tool available for Java developers. It is similar to Apache Maven, but does not support project management and dependency management features like Maven. It's a pure build tool.

You can run Selenium WebDriver tests using Ant via command line or through continuous integration (CI) tools such as Jenkins.

In this recipe, we will add Ant support to the SeleniumCookbook project created in the Configuring Selenium WebDriver test development environment for Java with Eclipse and Maven recipe.

Getting ready

You can also download and configure Ant from http://ant.apache.org/bindownload.cgi for other OS platforms.

Windows users can download and install WinAnt on Windows. WinAnt comes with an installer that will configure Ant through the installer. The WinAnt installer is available at http://code.google.com/p/winant/.

This recipe uses WinAnt on the Windows OS.

You will also need Selenium WebDriver and JUnit JAR files. You can download Selenium JAR file from http://selenium-release.storage.googleapis.com/ and JUnit JAR file from https://github.com/junit-team/junit/wiki/Download-and-Install.

How to do it...

Let's set up the SeleniumCookbook created in the previous recipe project for Ant with the following steps:

  1. Create a lib folder and copy the JAR files for the dependencies used for this project, that is, Selenium WebDriver and JUnit, to the lib folder, as shown in screenshot below:
    How to do it...
  2. Create the build.xml file in the project folder with the following XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <project name="test" default="exec" basedir=".">
    
        <property name="src" value="./src" />
        <property name="lib" value="./lib" />
        <property name="bin" value="./bin" />
        <property name="report" value="./report" />
        <path id="test.classpath">
            <pathelement location="${bin}" />
            <fileset dir="${lib}">
                <include name="**/*.jar" />
            </fileset>
        </path>
    
        <target name="init">
            <delete dir="${bin}" />
            <mkdir dir="${bin}" />
        </target>
    
        <target name="compile" depends="init">
            <javac source="1.8" srcdir="${src}" fork="true"
                destdir="${bin}" >
                <classpath>
                    <pathelement path="${bin}" />
                    <fileset dir="${lib}">
                      <include name="**/*.jar" />
                    </fileset>
                </classpath>
            </javac>
        </target>
    
        <target name="exec" depends="compile">
            <delete dir="${report}" />
            <mkdir dir="${report}" />
                <mkdir dir="${report}/xml" />
            <junit printsummary="yes" haltonfailure="no">
                <classpath>
                    <pathelement location="${bin}" />
                    <fileset dir="${lib}">
                        <include name="**/*.jar" />
                    </fileset>
                </classpath>
    
                <test name="com.secookbook.examples.chapter1.GoogleSearchTest"
                    haltonfailure="no" todir="${report}/xml"
                    outfile="TEST-result">
                    <formatter type="xml" />
                </test>
            </junit>
            <junitreport todir="${report}">
                <fileset dir="${report}/xml">
                    <include name="TEST*.xml" />
                </fileset>
                <report format="frames"
                    todir="${report}/html" />
            </junitreport>
        </target>
    </project>
  3. Navigate to the project directory through the command line and type the following command:
    ant
    

    This will trigger the build process. You will see the test running. At the end, Ant will create a report folder in the project folder. Navigate to the html subfolder in the report folder and open the index.html file to view the results.

How it works...

Ant needs a build.xml file with all the configurations and steps required to build the project. We can add steps for report generation, sending e-mail notification, and so on to build.xml. Ant provides a very dynamic framework for defining steps in the build process.

Ant also needs the necessary library/JAR files to be copied in the lib folder, which are needed for building the project.

Ant scans for the complete set of tests in the project and executes these tests in a way similar to Maven.

Configuring Microsoft Visual Studio for Selenium WebDriver test development

Selenium WebDriver provides .NET bindings to develop Selenium tests with the .NET platform. To use the Selenium WebDriver API along with .NET, you need to refer the Selenium WebDriver libraries to the project. Microsoft Visual Studio being the major IDE used in the .NET world, setting up the Selenium WebDriver support has become easier with NuGet Package Manager (http://nuget.org/).

This recipe explains the process of setting up Selenium WebDriver in Microsoft Visual Studio 2013 using NuGet.

Getting ready

NuGet comes bundled with Microsoft Visual Studio 2012 onwards. However, for Microsoft Visual Studio 2010, you will need to download and install NuGet from http://nuget.codeplex.com.

How to do it...

Let's configure Microsoft Visual Studio 2013 to develop Selenium WebDriver tests using the following steps:

  1. Launch the Microsoft Visual Studio.
  2. Create a new project by selecting File | New | Project from the main menu.
  3. In the New Project dialog box, select Visual C# | Test | Unit Test Project. Name the project as SeleniumCookbook and click on the OK button, as shown in the following screenshot:
    How to do it...
  4. Next, add Selenium WebDriver packages using NuGet. Right-click on the SeleniumCookbook solution in Solution Explorer and select Manage NuGet Packages…, as shown in the following screenshot:
    How to do it...
  5. On the SeleniumCookbook - Manage NuGet Packages dialog box, select Online and search for the WebDriver package. The search will result in the suggestions shown in the following screenshot:
    How to do it...
  6. Select Selenium WebDriver from the list and click on the Install button. Repeat this step for Selenium WebDriver Support Classes. Successful installation will show a green tick mark for both the packages, as shown in the following screenshot:
    How to do it...
  7. Close the SeleniumCookbook - Manage NuGet Packages dialog box.
  8. Expand the References tree for the SeleniumCookbook solution in Solution Explorer. References for WebDriver are added to the project as shown in the following screenshot:
    How to do it...
  9. The SeleniumCookbook project is ready for test development. You can go on adding new tests as needed.

How it works...

NuGet Package Manager adds the external dependencies to Microsoft Visual Studio projects. It lists all available packages and automatically downloads and configures packages to the project. It also installs dependencies for the selected packages automatically. This saves a lot of effort in configuring the projects initially.

Configuring Selenium WebDriver for Python and Ruby

Along with Java and C#, Selenium WebDriver can also be used with various other programming languages. Among these, Python and Ruby are popular choices to create Selenium WebDriver tests. In this recipe, you will see how to install Selenium WebDriver client libraries in Python and Ruby.

Getting ready

You will need Python or Ruby installed before installing the Selenium WebDriver client library.

Installing Python

You can download and install the latest Python version from https://www.python.org/. In this recipe, Python 3.4 is used.

Installing Ruby

Similarly, you can download and install the latest Ruby version from https://www.ruby-lang.org/en/installation/. In this recipe, Ruby 2.1.3 is used.

How to do it...

Installation and setting up Selenium WebDriver with Python or Ruby is simple using following steps.

Installing Selenium WebDriver with Python

You can install Selenium WebDriver with Python using the pip tool with the following command line:

pip install selenium

This will get the latest version of Selenium WebDriver Python client library installed. That's it.

Let's create a simple test in Python using this installation. Create a google_search.py file in your favorite editor or IDE and copy the following code:

import unittest
from selenium.webdriver.support import expected_conditions
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait


class GoogleSearch(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.com/"

    def test_google_search(self):
        driver = self.driver
        driver.get(self.base_url)

        element = driver.find_element_by_idname("q")
        element.clear()
        element.send_keys("Selenium testing tools cookbook")
        element.submit()

        WebDriverWait(driver, 30)\
            .until(expected_conditions.title_contains("Selenium testing tools cookbook"))
        self.assertEqual(driver.title, "Selenium testing tools cookbook - Google Search")

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main(verbosity=2, warnings="ignore")

You can run this test using the following command line:

python google_search.py

The Python interpreter will execute the test and you will see a Firefox window being opened and performing the search operation on Google.com. At the end of the execution you will see the results, as shown in the following screenshot:

Installing Selenium WebDriver with Python

Installing Selenium WebDriver with Ruby

You can install Selenium WebDriver with Ruby using the gem tool with following command line:

gem install selenium-webdriver

This will get the latest version of Selenium WebDriver Ruby client library installed. That's it.

Let's create a simple test in Ruby using this installation. Create a google_search.rb file in your favorite editor or IDE and copy the following code:

require "selenium-webdriver"
gem "test-unit"
require "test/unit"

class GoogleSearch < Test::Unit::TestCase
  def setup
    @driver = Selenium::WebDriver.for :firefox
    @base_url = "https://www.google.com/"
    @driver.manage.timeouts.implicit_wait = 30
  end

  def test_google_search
    @driver.get(@base_url)

    element = @driver.find_element(:name, "q")
    element.clear
    element.send_keys "Selenium testing tools cookbook"
    element.submit()

    wait = Selenium::WebDriver::Wait.new(:timeout => 10)
    wait.until { @driver.title.include? "Selenium testing tools cookbook" }

    assert_equal "Selenium testing tools cookbook - Google Search", @driver.title
  end

  def teardown
    @driver.quit
  end
end

You can run this test using the following command line:

ruby google_search.rb

Ruby interpreter will execute the test and you will see a Firefox window being opened and performing the search operation on Google.com. At the end of the execution you will see the results, as shown in the following screenshot:

Installing Selenium WebDriver with Ruby

How it works...

Selenium WebDriver is supported on various programming languages. For each supported language, a client library or language binding is published by the Selenium developers. These client libraries have Selenium WebDriver classes and functions that are needed to create automation scripts.

These libraries can be installed using package installers available with the respective languages. In this case, we used pip for Python, which connected to the PyPI (Python Package Index) source using the Internet, downloaded the latest Selenium WebDriver Python client library and installed with the Python directory. Similarly, Selenium WebDriver Ruby Gem is installed using the gem utility.

Setting up Internet Explorer Driver Server

We saw how to automate the Firefox browser in previous recipes. Using Firefox was straightforward. In order to execute test scripts on the Internet Explorer browser, we need to use InternetExplorerDriver and a standalone Internet Explorer Driver Server executable.

Let's setup InternetExplorerDriver and create tests for testing the search feature on Internet Explorer.

Getting ready

You need to download Internet Explorer Driver Server from http://docs.seleniumhq.org/download/. It is available in both 32bit and 64bit versions.

After downloading the IEDriver server, unzip and copy the file to the same directory in which the scripts are stored.

How to do it...

Let's create a test that uses Internet Explorer Driver Server with the following steps:

  1. In Eclipse, create a new folder named drivers in the src/test/resources folder of the SeleniumCookbook project. Copy the IEDriverServer.exe file to this folder, as shown in the following screenshot:
    How to do it...
  2. Add a new test and name it as GoogleSearchTestOnIE, and add the following code:
    package com.secookbook.examples.chapter01;
    
    import org.openqa.selenium.ie.InternetExplorerDriver;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.By;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.junit.*;
    
    import static org.junit.Assert.*;
    
    public class GoogleSearchTestOnIE {
    
      private WebDriver driver;
    
      @Before
      public void setUp() {
        System.setProperty("webdriver.ie.driver",
            "src/test/resources/drivers/IEDriverServer.exe");
    
        DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
    
        caps.setCapability(
            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
            true);
    
        // Launch Internet Explorer
        driver = new InternetExplorerDriver(caps);
        // Maximize the browser window
        driver.manage().window().maximize();
        // Navigate to Google
        driver.get("http://www.google.com");
      }
    
      @Test
      public void testGoogleSearch() {
        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));
    
        // Enter something to search for
        element.sendKeys("Selenium testing tools cookbook");
    
        // Now submit the form. WebDriver will find
        // the form for us from the element
        element.submit();
    
        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return d.getTitle().toLowerCase()
                .startsWith("selenium testing tools cookbook");
          }
        });
    
        assertEquals("Selenium testing tools cookbook - Google Search",
            driver.getTitle());
      }
    
      @After
      public void tearDown() throws Exception {
        // Close the browser
        driver.quit();
      }
    }

    Execute this test and you will see the Internet Explorer window being launched and all the steps executed.

How it works...

Internet Explorer Driver Server is a stand-alone server executable that implements WebDriver's JSON-wire protocol, which works as a glue between the test script and Internet Explorer, as shown in following diagram:

How it works...

The tests should specify the path of the IEDriverServer executable before creating the instance of Internet Explorer. This is done by setting the webdriver.ie.driver property as shown in following code:

System.setProperty("webdriver.ie.driver",
    "src/test/resources/drivers/IEDriverServer.exe");

Tip

We can also specify a path externally through the Dwebdriver.ie.driver option using Maven command line options. In this case, we don't need to set this property in test.

Internet Explorer Driver Server supports automating major IE versions on Windows XP, Vista, Windows 7, and Windows 8 operating systems.

Note

For more information on InternetExplorerDriver, please visit https://code.google.com/p/selenium/wiki/InternetExplorerDriver.

We need to create an instance of the InternetExplorerDriver class, which will connect to the Internet Explorer Driver Server to launch the Internet Explorer, shown as follows. It will then run the Selenium commands, which we will call by using various WebDriver and WebElement methods from the test script:

DesiredCapabilities caps = new DesiredCapabilities().internetExplorer();

caps.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);

// Launch Internet Explorer
driver = new InternetExplorerDriver(caps);

We used the DesiredCapabilities class to set the INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS capability, which defines to ignore the browser protected mode settings during the start by IEDriverServer.

There's more…

Selenium provides the ability to run tests on remote machines by using the RemoteWebDriver class. We can configure any browser that Selenium supports for executing tests on a remote machine. To run tests on a remote machine, we need to run the Selenium Server and the Internet Explorer Driver Server on a remote machine and use RemoteWebDriverClass, as shown in the following code sample:

DesiredCapabilities caps = new DesiredCapabilities().internetExplorer();

caps.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);

// Connect with Remote Selenium Server with specified URL and capabilities
driver = new RemoteWebDriver(new URL("http://192.168.1.3:4444/hub/wd"), caps);

We can connect any browser to a remote server using the preceding method.

Setting up ChromeDriver for Google Chrome

Similar to Internet Explorer, in order to execute test scripts on the Google Chrome browser, we need to use ChromeDriver and a standalone ChromeDriver executable.

ChromeDriver is maintained by the Google Chromium team. You can find more information at https://sites.google.com/a/chromium.org/chromedriver/.

Let's setup ChromeDriver and create a test for testing the search feature on Google Chrome.

Getting ready

You need to download ChromeDriver from https://sites.google.com/a/chromium.org/chromedriver/downloads.

How to do it...

  1. After downloading the ChromeDriver server, unzip and copy the file to the driver's directory in the src/test/resources folder, as shown in the following screenshot:
    How to do it...

    Note

    On Linux and Mac operating systems, the chromdriver file needs to be made executable using the chmod +x command filename or the chmod 775filename command.

  2. Add a new test and name it as GoogleSearchTestOnChrome.java, and add the following code:
    package com.secookbook.examples.chapter01;
    
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.By;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.junit.*;
    
    import static org.junit.Assert.*;
    
    public class GoogleSearchTestOnChrome {
    
      private WebDriver driver;
    
      @Before
      public void setUp() {
        System.setProperty("webdriver.chrome.driver",
            "./src/test/resources/drivers/chromedriver.exe");
    
        // Launch Chrome
        driver = new ChromeDriver();
        // Maximize the browser window
        driver.manage().window().maximize();
        // Navigate to Google
        driver.get("http://www.google.com");
      }
    
      @Test
      public void testGoogleSearch() {
        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));
    
        // Enter something to search for
        element.sendKeys("Selenium testing tools cookbook");
    
        // Now submit the form. WebDriver will find
        // the form for us from the element
        element.submit();
    
        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return d.getTitle().toLowerCase()
                .startsWith("selenium testing tools cookbook");
          }
        });
    
        assertEquals("Selenium testing tools cookbook - Google Search",
            driver.getTitle());
      }
    
      @After
      public void tearDown() throws Exception {
        // Close the browser
        driver.quit();
      }
    }

    Execute this test and you will see a Chrome window being launched and all the steps executed.

How it works...

ChromeDriver is a standalone server executable that implements WebDriver's JSON-wire protocol and works as a glue between the test script and Google Chrome, as shown in the following diagram:

How it works...

Note

For more information on ChromeDriver please visit https://code.google.com/p/selenium/wiki/ChromeDriver.

The tests should specify the path of the ChromeDriver executable before creating the instance of Chrome. This is done by setting the webdriver.chrome.driver property as shown in the following code:

System.setProperty("webdriver.chrome.driver","src/test/resources/drivers/chromedriver.exe");
    "src/test/resources/drivers/chromedriver.exe");

We can also specify a path externally through the –Dwebdriver.chrome.driver option using Maven command line options. In this case, we don't need to set up this property in test; we need to create an instance of ChromeDriver class that will connect to the ChromeDriver Server, as shown in the following code. It will then run the Selenium commands that we will call by using various WebDriver and WebElement methods from the test script:

driver = new ChromeDriver();

Setting up Microsoft WebDriver for Microsoft Edge

Microsoft Edge is a new web browser launched with Microsoft Windows 10. Microsoft Edge implements the W3C WebDriver standard and provides in-built support for Selenium WebDriver.

Similar to Internet Explorer, in order to execute test scripts on the Microsoft Edge browser, we need to use EdgeDriver class and a standalone Microsoft WebDriver Server executable.

Microsoft WebDriver Server is maintained by the Microsoft Edge development team. You can find more information at https://msdn.microsoft.com/en-us/library/mt188085(v=vs.85).aspx.

Let's set up Microsoft WebDriver Server and create a test for testing the search feature on Microsoft Edge.

Getting ready

You need to download and install Microsoft WebDriver Server on Windows 10 from https://www.microsoft.com/en-us/download/details.aspx?id=48212.

How to do it...

Add a new test and name it as GoogleSearchTestOnEdge.java and add the following code:

package com.secookbook.examples.chapter01;

import static org.junit.Assert.*;

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.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class GoogleSearchTestOnEdge {

  private WebDriver driver;

  @Before
  public void setUp() {
    System.setProperty("webdriver.edge.driver",
        "C:\\Program Files (x86)\\Microsoft Web Driver\\MicrosoftWebDriver.exe");

    EdgeOptions options = new EdgeOptions();
    options.setPageLoadStrategy("eager");

    // Launch a new Edge instance
    driver = new EdgeDriver(options);

    // Navigate to Google
    driver.get("http://www.google.com");
  }

  @Test
  public void testGoogleSearch() {
    // Find the text input element by its name
    WebElement element = driver.findElement(By.name("q"));

    // Clear the existing text value
    element.clear();

    // Enter something to search for
    element.sendKeys("Selenium testing tools cookbook");

    WebElement button = driver.findElement(By.name("btnG"));
    button.click();

    // Google's search is rendered dynamically with JavaScript.
    // Wait for the page to load, timeout after 10 seconds
    new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
      public Boolean apply(WebDriver d) {
        return d.getTitle().toLowerCase()
            .startsWith("selenium testing tools cookbook");
      }
    });

    assertEquals("Selenium testing tools cookbook - Google Search",
        driver.getTitle());
  }
  @After
  public void tearDown() throws Exception {
    // Close the browser
    driver.quit();
  }
}

Execute this test and you will see a Microsoft Edge window being launched and all the steps executed.

How it works...

Microsoft WebDriver Server is a standalone server executable that implements WebDriver's JSON-wire protocol, that works as a glue between the test script and the Microsoft Edge browser, as shown in the following diagram:

How it works...

The tests should specify the path of Microsoft WebDriver Server executable before creating the instance of Microsoft Edge. This is done by setting the webdriver.edge.driver property as shown in the following code:

System.setProperty("webdriver.edge.driver",
        "C:\\Program Files (x86)\\Microsoft Web Driver\\MicrosoftWebDriver.exe");

Tip

We can also specify a path externally through the –Dwebdriver.edge.driver option using the Maven command line options. In this case, we don't need to set up this property in test.

Left arrow icon Right arrow icon

Key benefits

  • Learn to leverage the power of Selenium WebDriver with simple examples that illustrate real-world problems and their workarounds
  • Explains the testing of mobile applications with Appium for mobile platforms such as iOS and Android
  • A pragmatic manual with engaging recipes and attractive screenshots to test your web applications efficiently

Description

This book is an incremental guide that will help you learn and use the advanced features of the Selenium toolset including the WebDriver API in various situations to build a reliable test automation. You start off by setting up the test development environment and gain tips on the advanced locater strategy and the effective use of the Selenium WebDriver API. After that, the use of design patterns such as data - driven tests and PageFactory are demonstrated. You will then be familiarised with extending Selenium WebDriver API by implementing custom tasks and setting up your own distributed environment to run tests in parallel for cross-browser testing. Finally, we give you some tips on integrating Selenium WebDriver with other popular tools and testing mobile applications. By the end of this book, you will have learned enough to solve complex testing issues on your own.

Who is this book for?

This book is intended for software quality assurance/testing professionals, software project managers, or software developers with prior experience in using Selenium and Java to test web-based applications. This books also provides examples for C#, Python and Ruby users.

What you will learn

  • Understand how the locators work and use various locator methods to build reliable tests
  • Build reliable and maintainable tests with the Selenium WebDriver API
  • Use the PageFactory pattern to build a robust and easy to maintain test framework
  • Build data-driven tests and extend Selenium API to implement custom steps and checks
  • Integrate and use ATDD/BDD tools such as Cucumber, SpecFlow, Capybara, and Behave with the Selenium WebDriver API
  • Set up iPhone/iPad and Android simulators and devices to test your mobile web application with Appium
  • Set up Selenium Grid for faster and parallel running of tests, increasing test coverage and reducing test execution time for cross-browser testing
  • Build extended Selenium WebDriver tests for additional coverage
Estimated delivery fee Deliver to Denmark

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 30, 2015
Length: 374 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392512
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Denmark

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Oct 30, 2015
Length: 374 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392512
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 73.98
Learning Selenium Testing Tools - Third Edition
€36.99
Selenium Testing Tools Cookbook Second Edition
€36.99
Total 73.98 Stars icon
Banner background image

Table of Contents

15 Chapters
1. Getting Started Chevron down icon Chevron up icon
2. Finding Elements Chevron down icon Chevron up icon
3. Working with Elements Chevron down icon Chevron up icon
4. Working with Selenium API Chevron down icon Chevron up icon
5. Synchronizing Tests Chevron down icon Chevron up icon
6. Working with Alerts, Frames, and Windows Chevron down icon Chevron up icon
7. Data-Driven Testing Chevron down icon Chevron up icon
8. Using the Page Object Model Chevron down icon Chevron up icon
9. Extending Selenium Chevron down icon Chevron up icon
10. Testing HTML5 Web Applications Chevron down icon Chevron up icon
11. Behavior-Driven Development Chevron down icon Chevron up icon
12. Integration with Other Tools Chevron down icon Chevron up icon
13. Cross-Browser Testing Chevron down icon Chevron up icon
14. Testing Applications on Mobile Browsers Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(12 Ratings)
5 star 33.3%
4 star 66.7%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Yang Shanel Wang Jun 21, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I don’t know why I bought this book so author is winner because Science can include great sense of humor too. The purpose of invention of computer no matter software and hardware is to create convenience and happiness so human beings will have confidence stop fighting, no sadness, no discrimination.Computer codes are creatively changing and quality of production are improving because people love what they do so they never be dangerous to think consumers owe anything. I am lucky I am one of benefits especially it is very tough in recycle industry. I am grateful a lot of people put efforts to contribute, think others situations, and make people happy meanwhile it is bless I am around those people with good humble heart.
Amazon Verified review Amazon
Alexander Afanasyev Dec 27, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
What is really good about this book is that it contains tons of examples and recipes that you can try out in practice right away.The book contains quite a thorough example-based overview of the Selenium WebDriver API, from different element location techniques to mobile testing and selenium grids.
Amazon Verified review Amazon
Arun Motoori Dec 30, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love this book among all the books available on Selenium. Few books help you get started, but this book stays with you from the beginning and continues to stay with you as reference. This book covers basic to advanced concepts of selenium in a simple and practical way. Topics like Configuring the Environment for developing Automation Scripts , Locators for finding various UI elements, Selenium API Commands along with their practical usage, latest framework concepts and many more are explained very well in a practical way. If you want to start learning or improve your knowledge on Selenium, just go for this book without any second thought.
Amazon Verified review Amazon
Priyanka Jan 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Helpful
Amazon Verified review Amazon
Amazon Customer Dec 31, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Its worthy
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela