Selenium:Environment Setup

In order to develop Selenium RC or WebDriver scripts, users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps.
  • Download and Install Java
  • Download and Configure Eclipse
  • Configure FireBug and FirePath
  • Configure Selenium RC
  • Configure Selenium WebDriver

Download and Install Java

We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Let us see how to download and install Java.
Step 1 : Navigate to the URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 2 : Go to "Downloads" section and select "JDK Download".
Selenium IDE 30
Step 3 : Select "Accept License Agreement" radio button.
Selenium IDE 31
Step 4 : Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk.
Selenium IDE 32
Step 5 : Run the downloaded exe file to launch the Installer wizard. Click 'Next' to continue.
Selenium IDE 33
Step 6 : Select the features and click 'Next'.
Selenium IDE 34
Step 7 : The installer is extracted and its progress is shown in the wizard.
Selenium IDE 35
Step 8 : The user can choose the install location and click 'Next'.
Selenium IDE 36
Step 9 : The installer installs the JDK and new files are copied across.
Selenium IDE 37
Step 10 : The Installer installs successfully and displays the same to the user.
Selenium IDE 38
Step 11 : To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error.
Selenium IDE 48

Download and Configure Eclipse

Step 1 : Navigate to the URL: http://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture.
Selenium IDE 39
Step 2 : Click the 'Download' button.
Selenium IDE 40
Step 3 : The download would be in a Zipped format. Unzip the contents.
Selenium IDE 41
Step 4 : Locate Eclipse.exe and double click on the file.
Selenium IDE 42
Step 5 : To configure the workspace, select the location where the development has to take place.
Selenium IDE 43
Step 6 : The Eclipse window opens as shown below.
Selenium IDE 44

Configure FireBug and FirePath

To work with Selenium RC or WebDriver, we need to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins.
Step 1 : Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin.
Selenium IDE 62
Step 2 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Selenium IDE 63
Step 3 : After installing, we can launch the plugin by navigating to "Web Developer" >> "Firebug".
Selenium IDE 64
Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/"
Selenium IDE 65
Step 5 : The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Selenium IDE 66
Step 6 : Now launch "Firebug" by navigating to "Tools" >> "Webdeveloper" >> "Firebug".
Selenium IDE 67

Example

Now let us understand how to use FireBug and FirePath with an example. For demonstration, we will use www.google.com and capture the properties of the text box of "google.com".
Step 1 : First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact.
Selenium IDE 68
Step 2 : To fetch the XPath of the object, go to 'firepath' tab and perform the following steps.
  • Click the Spy icon.
  • Select the Control for which we would like to capture the XPath
  • XPath of the selected control would be generated.
Selenium IDE 69

Configure Selenium RC

Now let us look at how to configure Selenium Remote control. We will understand how to develop scripts with Selenium RC in later chapters, however for now, we will understand just the configuration part of it.
Step 1 : Navigate to the Selenium downloads section http://www.seleniumhq.org/download/ and download Selenium Server by clicking on its version number as shown below.
Selenium IDE 45
Step 2 : After downloading, we need to start the Selenium Server. To do so, open command prompt and navigate to the folder where the downloaded JAR file is kept as shown below.
Selenium IDE 46
Step 3 : To start the server, use the command 'java -jar <<downloaded jar name >> and if java JDK is installed properly, you would get a success message as shown below. Now we can start writing Selenium RC scripts.
Selenium IDE 47

Configure Selenium WebDriver

Now let us look at how to configure Selenium WebDriver. We will understand how to develop scripts with Selenium WebDriver in later chapters, however for now, we will understand just the configuration part of it.
Step 1 : Navigate to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below.
Selenium IDE 49
Step 2 : The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder.
Selenium IDE 49
Step 3 : The Unzipped contents would be displayed as shown below. How to map it to the project folder and how to start scripting would be dealt in the webDriver chapter.
Selenium IDE 51

Selenium Introduction


                                                 Selenium

Selenium is an open-source and a portable automated software testing tool for testing web applications. It has capabilities to operate across different browsers and operating systems. Selenium is not just a single tool but a set of tools that helps testers to automate web-based applications more efficiently.
Let us now understand each one of the tools available in the Selenium suite and their usage.
ToolDescription
Selenium IDESelenium Integrated Development Environment (IDE) is a Firefox plugin that lets testers to record their actions as they follow the workflow that they need to test.
Selenium RCSelenium Remote Control (RC) was the flagship testing framework that allowed more than simple browser actions and linear execution. It makes use of the full power of programming languages such as Java, C#, PHP, Python, Ruby and PERL to create more complex tests.
Selenium WebDriverSelenium WebDriver is the successor to Selenium RC which sends commands directly to the browser and retrieves results.
Selenium GridSelenium Grid is a tool used to run parallel tests across different machines and different browsers simultaneously which results in minimized execution time.

Advantages of Selenium

QTP and Selenium are the most used tools in the market for software automation testing. Hence it makes sense to compare the pros of Selenium over QTP.
SeleniumQTP
Selenium is an open-source tool.QTP is a commercial tool and there is a cost involved in each one of the licenses.
Can be extended for various technologies that expose DOM.Limited add-ons and needs add-ons for each one of the technologies.
Has capabilities to execute scripts across different browsers.Can run tests in specific versions of Firefox , IE, and Chrome.
Can execute scripts on various operating systems.Works only with Windows.
Supports mobile devices.Supports mobile devices with the help of third-party tools.
Executes tests within the browser, so focus is NOT required while script execution is in progress.Needs Focus during script execution, as the tool acts on the browser (mimics user actions).
Can execute tests in parallel with the use of Selenium Grids.QTP cannot execute tests in parallel, however integrating QTP with QC allows testers to execute in parallel. QC is also a commercial tool.

Disadvantages of Selenium

Let us now discuss the pitfalls of Selenium over QTP.
SeleniumQTP
Supports only web based applications.Can test both web and desktop applications.
No feature such as Object Repository/Recovery ScenarioQTP has built-in object repositories and recovery scenarios.
No IDE, so the script development won't be as fast as QTP.More intuitive IDE; automation can be achieved faster.
Cannot access controls within the browser.Can access controls within the browser such as favorites bar, backward, and forward buttons.
No default test report generation.Default test result generation within the tool.
For parameterization, users has to rely on the programming language.Parameterization is built-in and easy to implement.

Selenium:Interview Questions

frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
Q #28) When do we use findElement() and findElements()?
findElement(): findElement() is used to find the first element in the current web page matching to the specified locator value. Take a note that only first matching element would be fetched.
Syntax:
WebElement element =driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page matching to the specified locator value. Take a note that all the matching elements would be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList =driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
Q #29) How to find more than one web element in the list?
At times, we may come across elements of same type like multiple hyperlinks, images etc arranged in an ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of code and this can be done using WebElement List.
Sample Code
1// Storing the list
2List <WebElement> elementList = driver.findElements(By.xpath("//div[@id='example']//ul//li"));
3// Fetching the size of the list
4int listSize = elementList.size();
5for (int i=0; i<listSize; i++)
6{
7// Clicking on each service provider link
8serviceProviderLinks.get(i).click();
9// Navigating back to the previous page that stores link to service providers
10driver.navigate().back();
11}
Q #30) What is the difference between driver.close() and driver.quit command?
close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window that is being currently accessed by the WebDriver. The command neither requires any parameter nor does is return any value.
quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as close() method, the command neither requires any parameter nor does is return any value.
Q #31) Can Selenium handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using Selenium.
Q #32) How can we handle web based pop up?
WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface. There are the four methods that we would be using along with the Alert interface.
  • void dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop up window appears.
  • void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
Syntax:
// accepting javascript alert 
                Alert alert = driver.switchTo().alert();
alert.accept();
Q #33) How can we handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support testing of windows based applications. However Selenium alone can’t help the situation but along with some third party intervention, this problem can be overcome. There are several third party tools available for handling window based pop ups along with the selenium like AutoIT, Robot class etc.
Q #34) How to assert title of the web page?
//verify the title of the web page
assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the page”));
Q #35) How to mouse hover on a web element using WebDriver?
WebDriver offers a wide range of interaction utilities that the user can exploit to automate mouse and keyboard events. Action Interface is one such utility which simulates the single user interactions.
Thus, In the following scenario, we have used Action Interface to mouse hover on a drop down which then opens a list of options.
Sample Code:
1// Instantiating Action Interface
2Actions actions=new Actions(driver);
3// howering on the dropdown
4actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();
5// Clicking on one of the items in the list options
6WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
7subLinkOption.click();
Q #36) How to retrieve css properties of an element?
The values of the css properties can be retrieved using a get() method:
Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);
Q #37) How to capture screenshot in WebDriver?
1import org.junit.After;
2import org.junit.Before;
3import org.junit.Test;
4import java.io.File;
5import java.io.IOException;
6import org.apache.commons.io.FileUtils;
7import org.openqa.selenium.OutputType;
8import org.openqa.selenium.TakesScreenshot;
9import org.openqa.selenium.WebDriver;
10import org.openqa.selenium.firefox.FirefoxDriver;
11
12public class CaptureScreenshot {
13       WebDriver driver;
14       @Before
15       public void setUp() throws Exception {
16            driver = new FirefoxDriver();
17            driver.get("https://google.com");
18     }
19     @After
20     public void tearDown() throws Exception {
21            driver.quit();
22     }
23
24     @Test
25     public void test() throws IOException {
26            // Code to capture the screenshot
27File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
28            // Code to copy the screenshot in the desired location
29FileUtils.copyFile(scrFile, newFile("C:\\CaptureScreenshot\\google.jpg"));                  
30     }
31}
Q #38) What is Junit?
Junit is a unit testing framework introduced by Apache. Junit is based on Java.
Q #39) What are Junit annotations?
Following are the Junit Annotations:
  • @Test: Annotation lets the system know that the method annotated as @Test is a test method. There can be multiple test methods in a single test script.
  • @Before: Method annotated as @Before lets the system know that this method shall be executed every time before each of the test method.
  • @After: Method annotated as @After lets the system know that this method shall be executed every time after each of the test method.
  • @BeforeClass: Method annotated as @BeforeClass lets the system know that this method shall be executed once before any of the test method.
  • @AfterClass: Method annotated as @AfterClass lets the system know that this method shall be executed once after any of the test method.
  • @Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.
Q #40) What is TestNG and how is it better than Junit?
TestNG is an advance framework designed in a way to leverage the benefits by both the developers and testers. With the commencement of the frameworks, JUnit gained an enormous popularity across the Java applications, Java developers and Java testers with remarkably increasing the code quality. Despite being easy to use and straightforward, JUnit has its own limitations which give rise to the need of bringing TestNG into the picture. TestNG is an open source framework which is distributed under the Apache software License and is readily available for download.
TestNG with WebDriver provides an efficient and effective test result format that can in turn be shared with the stake holders to have a glimpse on the product’s/application’s health thereby eliminating the drawback of WebDriver’s incapability to generate test reports. TestNG has an inbuilt exception handling mechanism which lets the program to run without terminating unexpectedly.
There are various advantages that make TestNG superior to JUnit. Some of them are:
  • Added advance and easy annotations
  • Execution patterns can set
  • Concurrent execution of test scripts
  • Test case dependencies can be set
Q #41) How to set test case priority in TestNG?
Setting Priority in TestNG
Code Snippet
1package TestNG;
2import org.testng.annotations.*;
3public class SettingPriority {
4      @Test(priority=0)
5      public void method1() {   
6      }
7      @Test(priority=1)
8      public void method2() {  
9      }
10      @Test(priority=2)
11      public void method3() {   
12      }
13}
Test Execution Sequence:
  1. Method1
  2. Method2
  3. Method3
Q #42) What is a framework?
Framework is a constructive blend of various guidelines, coding standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data injections etc. to pillar automation testing.
Q #43) What are the advantages of Automation framework?
  • Reusability of code
  • Maximum coverage
  • Recovery scenario
  • Low cost maintenance
  • Minimal manual intervention
  • Easy Reporting
Q #44) What are the different types of frameworks?
Below are the different types of frameworks:
  1. Module Based Testing Framework: The framework divides the entire “Application Under Test” into number of logical and isolated modules. For each module, we create a separate and independent test script. Thus, when these test scripts taken together builds a larger test script representing more than one module.
  2. Library Architecture Testing Framework: The basic fundamental behind the framework is to determine the common steps and group them into functions under a library and call those functions in the test scripts whenever required.
  3. Data Driven Testing Framework: Data Driven Testing Framework helps the user segregate the test script logic and the test data from each other. It lets the user store the test data into an external database. The data is conventionally stored in “Key-Value” pairs. Thus, the key can be used to access and populate the data within the test scripts.
  4. Keyword Driven Testing Framework: The Keyword driven testing framework is an extension to Data driven Testing Framework in a sense that it not only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script into an external data file.
  5. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more than one above mentioned frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of associated frameworks.
  6. Behavior Driven Development Framework: Behavior Driven Development framework allows automation of functional validations in easily readable and understandable format to Business Analysts, Developers, Testers, etc.
Q #45) How can I read test data from excels?
Test data can efficiently be read from excel using JXL or POI API.See detailed tutorial here.
Q #46) What is the difference between POI and jxl jar?
#JXL jarPOI jar
1JXL supports “.xls” format i.e. binary based format. JXL doesn’t support Excel 2007 and “.xlsx” format i.e. XML based formatPOI jar supports all of these formats
2JXL API was last updated in the year 2009POI is regularly updated and released
3The JXL documentation is not as comprehensive as that of POIPOI has a well prepared and highly comprehensive documentation
4JXL API doesn’t support rich text formattingPOI API supports rich text formatting
5JXL API is faster than POI APIPOI API is slower than JXL API
Q #47) What is the difference between Selenium and QTP?
FeatureSeleniumQuick Test Professional (QTP)
Browser CompatibilitySelenium supports almost all the popular browsers like Firefox, Chrome, Safari, Internet Explorer, Opera etcQTP supports Internet Explorer, Firefox and Chrome. QTP only supports Windows Operating System
DistributionSelenium is distributed as an open source tool and is freely availableQTP is distributed as a licensed tool and is commercialized
Application under TestSelenium supports testing of only web based applicationsQTP supports testing of both the web based application and windows based application
Object RepositoryObject Repository needs to be created as a separate entityQTP automatically creates and maintains Object Repository
Language SupportSelenium supports multiple programming languages like Java, C#, Ruby, Python, Perl etcQTP supports only VB Script
Vendor SupportAs Selenium is a free tool, user would not get the vendor’s support in troubleshooting issuesUsers can easily get the vendor’s support in case of any issue
Q #48) Can WebDriver test Mobile applications?
WebDriver cannot test Mobile applications. WebDriver is a web based testing tool, therefore applications on the mobile browsers can be tested.
Q #49) Can captcha be automated?
No, captcha and bar code reader cannot be automated.
Q #50) What is Object Repository? How can we create Object Repository in Selenium?
Object Repository is a term used to refer to the collection of web elements belonging to Application Under Test (AUT) along with their locator values. Thus, whenever the element is required within the script, the locator value can be populated from the Object Repository. Object Repository is used to store locators in a centralized location instead of hard coding them within the scripts.
In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

Handling Dynamic Elements in Selenium WebDriver

                       Handling Dynamic Elements in Selenium WebDriver Dynamic elements are those elements which have identifiers that a...