19.2 WebDriver browser methods

19.2.1| getPageSource

Returns the page source of the last loaded page. The page source returned is a representation of the underlying DOM. It may not be formatted or escaped in the same way as the response sent from the server.

                                                                                                                                                           
            Syntex               java.lang.String getPageSource
      parameters            
      returns              The page source of the current page

                                                                                                                                                       

Write a code to open testinganswers.com and retrieve its page source

getPageSource in selenium


Note: If the page is modified after page reload (e.g. page refresh after selecting some list box option), then there is no guarantee that the returned page source text is of the reloaded page. WebDriver documentation can be referenced to know the exact behavior of the specific driver.


19.2.2| navigate

Simulates browser back, forward, refresh and navigate to options.

                                                                                                                                                           
            Syntex               WebDriver.Navigation navigate()
      parameters            
      returns              A WebDriver.Navigation that allows the 
                           selection of what to do next

                                                                                                                                                       

This method allows WebDriver test script to simulate user interactions with browsers such as navigating to specific URL, clicking on browser back or forward button, clicking on browser refresh button, etc. 


Simulates browser back, forward, refresh and navigate to options.




























19.2.3| getWindowHandles

Returns all browser windows of the WebDriver instance.

                                                                                                                                                         
            Syntex               java.util.Set<java.lang.String>
      parameters            
      returns              A set of window handles which can be used
                           to iterate over all the open windows.

                                                                                                                                                       

Suppose the user opens testinganswers.com and then clicks on the link available on the site in another/ new window. So, see how to handle all windows and perform an action on all the windows (Driver instances) in Selenium.


getWindowHandles in Selenium

19.2.4| getWindowHandle

Returns the currently active browser window of the WebDriver instance.

                                                                                                                                                         
            Syntex               java.lang.String getWindowHandle()
      parameters            
      returns              Returns the currently active window
                           handle. 

                                                                                                                                                       

Suppose the user opens testinganswers.com and then clicks on the link available on the site in another/ new window. So, see how to handle both windows and perform an action on both windows (Driver instances) in Selenium.

getWindowHandle in Selenium


19.1 WebDriver browser methods

WebDriver provides a variety of methods to simulate user actions on a browser. Some of those methods are described below 

19.1.1| get


Loads a new page in the current browser window. This is achieved using HTTP GET operation. This method blocks the WebDriver test execution until the page load is complete.


                                                                                                                                                             
            Syntex               get (java.lang.String URL)
      parameter            URL   - URL of the site to navigate to
      returns              void
                                                                                                                                                       


Write WebDriver code to open the Chrome browser and navigate to the https://www.testinganswers.com site

get



19.1.2| getCurrentUrl

Returns the current URL of the browser page

                                                                                                                                                           
            Syntex         java.lang.String getCurrentUrl
      parameter            
      returns        URL of the page currently loaded in the 
                     browser
                                                                                                                                                       


Write WebDriver code to open the Chrome browser, navigate to the https://www.testinganswers.com site and then verify that the current page is testinganswers.com or not.


getCurrentUrl


19.1.3| getTitle

Returns the title of the current web page

                                                                                                                                                          
            Syntex         java.lang.String getTitle
      parameter            
      returns        the title of the current web page with 
                     leading and trailing whitespace stripped or
                     null if one is not already set.
                                                                                                                                                       


Write WebDriver code to open the Chrome browser, navigate to the https://www.testinganswers.com site and then verify that the current page title is correct or not.


getTitle


19.1.4| findElements


Finds all the matched elements on the current page. This method continuously tries to identify the elements till zero or more elements are found or timeout time is reached, whichever happens first.

                                                                                                                                                          
            Syntex         java.util.List<WebElement> findElements(By by)
      parameter      by - the locating mechanism to use      
      returns        the list of all matched elements or an empty
                     list if no match is found.
                                                                                                                                                       

Find all-day elements of a calendar.


Find all-day elements of a calendar.










19.1.5| findElement


Finds the first matched web element on the current page. This method continuously tries to identify the elements until the element is found or timeout time is reached, whichever happens first. If no matched element is found until timeout time, then it returns an exception. This method implicitly waits to identify the element until the configured timeout is reached.

                                                                                                                                                          
            Syntex         WebElement findElement(By by)
      parameter      by - the locating mechanism to use      
      returns        the first matched elements else throws 
                     NoSuchElementException if no matched element
                     found
                                                                                                                                                       

Select an element from the calendar year drop-down.


18 Working with Browsers

A web browser is a software application that allows users to retrieve, present and traverse information resources on the World Wide Web (www). An information resource is identified by a Uniform Resource Identifier (URI). The information may be a web page, image, audio, video or any other content. There are various browsers available in the market as of now. These include internet explorer, chrome, firefox, safari, opera, etc. This chapter describes how to use the WebDriver method to simulate user actions on a firefox browser.

18.1.1| Introduction

  • Open Firefox Browser: WebDriver provided FirefoxDriver() class to open a new Firefox browser session. The following code shows how to create an instance of FirefoxDriver() and open the www.testinganswers.com site.
Open Firefox Browser

  • Open Chrome Browser: WebDriver provided ChromeDriver() class to open a new chrome browser session. The following code shows how to create an instance of ChromeDriver() and open the www.testinganswers.com site.
Open Chrome Browser

  • Open Internet Explorer Browser: WebDriver provided InternetExplorerDriver() class to open a new chrome browser session. The following code shows how to create an instance of InternetExplorerDriver() and open the www.testinganswers.com site.
Open Internet Explorer Browser


18.1.2| Choose a browser at run time

In Selenium WebDriver, we can automate test cases using Internet Explorer, Firefox, Chrome, etc browsers. Especially, in Cross Browser Testing. Cross Browser Testing is a type of functional test to check that your web application works as expected in different browsers. So, let's see, how to choose a browser at run time in Selenium WebDriver in below code piece

Choose a browser at run time


17.2 User Interface Map

17.2.1| Creating a UIMap class to read locators from UIMap.properties file

Now we will build a UIMap class to access locator information from a properties file.


UIMap.properties
UIMap.properties example part-1



UIMap.properties
UIMap.properties example part-2



UIMap.properties
UIMap.properties example part-3


17.2.2| Creating a sample Test

Now let us create a sample test that would use the UIMap properties file and UIMap class file to locate elements.

Following example opens amazon.in the login page and then uses UIMap file to locate login page elements.


UIMap.properties
Sample Test



17.1 User Interface Map

Selenium WebDriver API uses locator information to find elements on the page. Defining the locator information in the classes may result in duplication of element location information in various classes. Because of such duplication, it becomes increasingly difficult to maintain tests as the size of the test suite increases. Any change in element locator information requires updating of the element locator information in all the classes wherever it has been defined. Identifying classes which require an update and then updating them is a very time consuming and difficult task. In short, change identification and change implementation become a nightmare.

One way to solve this problem is to use the Page Object Model framework (Agile Automation Framework). In this framework, each page is used as a reusable class. All the elements of the page are defined in the same page class without any duplication. In order to avoid locator information duplication within the page class, the locator information is defined at the top of the page using @FindBy method.

Another way to resolve this problem is to create a repository which defines locator information of all the elements. This element repository is termed as Object or UI Map. A user interface (UI) Map helps in creating a one-point maintenance framework for elements' locator information.

UI Maps are easier to maintain. Maintaining all locator information in one place also helps to avoid duplication of elements' locator information. Whenever a change to a specific elements' locator information is required, it can be easily identified and changed in the UI Map. Making changes in one file is much simpler and easier rather than making changes in multiple files (class files or tests). Since changes are to be done in one file, change identification and change implementation are easier. Also, the UI Map can be version controlled.


17.1.1 | Creating Selenium Extension for UI Map using a properties file

In the following section, we will discuss how to extend Selenium WebDriver to develop a UI Map for amazon.in site login page. Firstly, a UI Map cab be any flat file or .properties file. Locator information can be defined as key-value pairs in the UI Map file. This UI Map cab be imported in all the page class files which need to interact with application front-end.


17.1.2 | Defining Locator information in UI Map

Let us first create a UIMap.properties file. The locator information can be added to this file as key-value pairs.  Assume the format for the defining key-value pairs to be: 

Defining Locator information in UI Map

Now let us define the locator information for amazon.in login page.






16.2 Annotation

16.2 | Custom Annotations

Java provides the flexibility to define custom annotations as per need. An annotation is defined with the at-sign (@) preceding the interface keyword. The following steps show how to create and use custom annotations.

  • Open Eclipse
  • Select the package where annotation needs to be created.
  • Right-click and select New → Annotation as shown in figure

Creating a new annotation file
Creating a new annotation file

  • Specify annotation name say RegressionTest.
The following code shows the annotation code with no annotations and parameters.

RegressionTest
RegressionTest

Above annotation can be directly used in code as:

UsingAnnotation
Use of Annotation

  • Annotate the annotation as required.
The following code shows how to create an annotation which defines the test type being automated (functional or regression). This annotation also defines the retention policy and the applicability of the TestDetails annotation.

Annotate the Annotation

  • Define the parameters of annotation, if any.
The following code below shows how to define two parameters for test information test developed by and test modified by.

Parameters of annotation
Parameters of annotation

  • Use the annotation while developing code wherever required.
The following code uses the annotation TestDetails for test 'testPurchaseOrder'.

Use of Annotation
Use of Annotation

16.1 Annotation

An annotation is a form of metadata that provides data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code which is annotated. The annotation has a number of uses and few of them are as follows: 

  • Annotation can be used by the compiler to detect errors or suppress warnings.
  • Annotations can be examined at runtime.
  • Software tools can be written that process annotation information to generate code, XML files, etc.

An important use of annotation in test automation is to define the test type (functional, regression) and test functional area (customer accounts, funds transfer, etc., for a banking application). Once this information is defined as an annotation in tests, the tool can be written to selectively execute a specific type of test. Also, the tool can provide info about the test coverage in each functional area.

16.1 | Built-in Annotations

Java provides some built-in annotations. Few of them are listed below:

  • @Override: Verifies that the specific method is an override. It causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  • @Deprecated: Marks the specific method as obsolete. It causes a compile-time error if the specific method is used.
  • @SuppressWarnings: Instructs the compiler to suppress the compile-time warnings which match the annotation parameters.

Section 'Interfaces' shows the use of @Override annotation.

Annotations can also be used to annotate annotations. Listed as follows are few annotations that define the behavior of an annotation:

  • @Retention: Specifies how the annotation is stored- whether in code only or compiles into the class or available at runtime through reflection.
  • @Documented: Marks another annotation for inclusion in the documentation.
  • @Target: Marks another annotation to restrict the kind of java elements the annotation may be applied to.
  • @Inherited: Marks another annotation to be inherited to a subclass of annotated class.