Selenium Interview Questions

Selenium Interview Questions

Q: What is Automation Testing?
A: Automation testing or Test Automation is a process of automating the manual process to test the application/system under test. Automation testing involves use to a separate testing tool which lets you create test scripts which can be executed repeatedly and doesn’t require any manual intervention.

Q: What are the benefits of Automation Testing?
A: Benefits of Automation testing are:
1.     Supports execution of repeated test cases
2.     Aids in testing a large test matrix
3.     Enables parallel execution
4.     Encourages unattended execution
5.     Improves accuracy thereby reducing human generated errors
6.     Saves time and money

Q: Why should Selenium be selected as a test tool?
A: Selenium
1.     is free and open source
2.     have a large user base and helping communities
3.     have cross Browser compatibility (Firefox, chrome, Internet Explorer, Safari etc.)
4.     have great platform compatibility (Windows, Mac OS, Linux etc.)
5.     supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
6.     has fresh and regular repository developments
7.     supports distributed testing

Q: What is Selenium? What are the different Selenium components?
A: Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms. Due to its existence in the open source community, it has become one of the most accepted tools amongst the testing professionals.
Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason it is referred to as a Suite. Each of these tools is designed to cater different testing and test environment requirements.
The suite package constitutes of the following sets of tools:
  • Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool. It is distributed as a Firefox Plugin.
  • Selenium Remote Control (RC) – Selenium RC is a server that allows user to create test scripts in a desired programming language. It also allows executing test scripts within the large spectrum of browsers.
  • Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.
  • Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.

Q: What are the testing types that can be supported by Selenium?
A: Selenium supports the following types of testing:
1.     Functional Testing
2.     Regression Testing

Q: What are the limitations of Selenium?
A: Following are the limitations of Selenium:
  • Selenium supports testing of only web based applications
  • Mobile applications cannot be tested using Selenium
  • Captcha and Bar code readers cannot be tested using Selenium
  • Reports can only be generated using third party tools like TestNG or Junit.
  • As Selenium is a free tool, thus there is no ready vendor support though the user can find numerous helping communities.
  • User is expected to possess prior programming language knowledge.

Q: What is the difference between Selenium IDE, Selenium RC and WebDriver?
A:
Feature
Selenium IDE
Selenium RC
WebDriver

Browser Compatibility
Selenium IDE comes as a Firefox plugin, thus it supports only Firefox
Selenium RC supports a varied range of versions of Mozilla Firefox, Google Chrome, Internet Explorer and Opera
WebDriver supports a varied range of versions of Mozilla Firefox, Google Chrome, Internet Explorer and Opera.
Also supports HtmlUnitDriver which is a GUI less or headless browser. 
Record and Playback
Selenium IDE supports record and playback feature
Selenium RC doesn't supports record and playback feature
WebDriver doesn't support record and playback feature
Server Requirement
Selenium IDE doesn't require any server to be started before executing the test scripts
Selenium RC requires server to be started before executing the test scripts
WebDriver doesn't require any server to be started before executing the test scripts
Architecture
Selenium IDE is a Javascript based framework
Selenium RC is a JavaScript based Framework
WebDriver uses the browser's native compatibility to automation
Object Oriented
Selenium IDE is not an object oriented tool
Selenium RC is semi object oriented tool
WebDriver is a purely object oriented tool
Dynamic Finders
(for locating web elements on a webpage)
Selenium IDE doesn't support dynamic finders
Selenium RC doesn't support dynamic finders
WebDriver supports dynamic finders
Handling Alerts, Navigations, Dropdowns
Selenium IDE doesn't explicitly provides aids to handle alerts, navigations, dropdowns
Selenium RC doesn't explicitly provides aids to handle alerts, navigations, dropdowns
WebDriver offers a wide range of utilities and classes that helps in handling alerts, navigations, and dropdowns efficiently and effectively.
WAP (iPhone/Android) Testing
Selenium IDE doesn't support testing of iPhone/Andriod applications
Selenium RC doesn't support testing of iPhone/Andriod applications
WebDriver is designed in a way to efficiently support testing of iPhone/Android applications. The tool comes with a large range of drivers for WAP based testing.
For example, AndroidDriver, iPhoneDriver 
Listener Support
Selenium IDE doesn't support listeners
Selenium RC doesn't support listeners
WebDriver supports the implementation of Listeners
Speed
Selenium IDE is fast as it is plugged in with the web-browser that launches the test. Thus, the IDE and browser communicates directly
Selenium RC is slower than WebDriver as it doesn't communicates directly with the browser; rather it sends selenese commands over to Selenium Core which in turn communicates with the browser.
WebDriver communicates directly with the web browsers. Thus making it much faster.

Q: When should I use Selenium IDE?
A: Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback feature makes it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

Q: What is Selenese?
A: Selenese is the language which is used to write test scripts in Selenium IDE.

Q: What are the different types of locators in Selenium?
A: Locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium:
  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector
  • DOM

Q: What is difference between assert and verify commands?
A: Assert: Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.

Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halts i.e. any failure during verification would not stop the execution and all the test steps would be executed.

Q: What is an Xpath?
A: Xpath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being markup languages and since they fall under the same umbrella, Xpath can be used to locate HTML elements.
The fundamental behind locating elements using Xpath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.

Q: What is the difference between “/” and “//” in Xpath?
A: Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.
Double Slash “//” - Double slash is used to create Xpath with relative path i.e. the xpath would be created to start selection from anywhere within the document.

Q: What is Same origin policy and how it can be handled?
A: The problem of same origin policy disallows to access the DOM of a document from an origin that is different from the origin we are trying to access the document.
Origin is a sequential combination of scheme, host and port of the URL. For example, for a URL http:// http://www.softwaretestinghelp.com/resources/, the origin is a combination of http, softwaretestinghelp.com, 80 correspondingly.
Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin that is different from where it was launched. For Example, if I have launched the JavaScript Program from “http://www.softwaretestinghelp.com”, then I would be able to access the pages within the same domain such as “http://www.softwaretestinghelp.com/resources” or “http://www.softwaretestinghelp.com/istqb-free-updates/”. The other domains like google.com, seleniumhq.org would no more be accessible.
So, In order to handle same origin policy, Selenium Remote Control was introduced.

Q: When should I use Selenium Grid?
A: Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution, testing under different environments and saving execution time remarkably.

Q: What do we mean by Selenium 1 and Selenium 2?
A: Selenium RC and WebDriver, in a combination are popularly known as Selenium 2. Selenium RC alone is also referred as Selenium 1.

Q: Which is the latest Selenium tool?
A: WebDriver

Q: How do I launch the browser using WebDriver?
A: The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();

Q: What are the different types of Drivers available in WebDriver?
A: The different drivers available in WebDriver are:
  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

Q: What are the different types of waits available in WebDriver?
1.     Implicit Wait
2.     Explicit Wait
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.

Q: How to type in a textbox using Selenium?
A: User can use sendKeys(“String to be entered”) to enter the string in the textbox.
Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);

Q: How can you find if an element in displayed on the screen?
A: WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.
1.     isDisplayed()
2.     isSelected()
3.     isEnabled()
Syntax:
isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

Q: How can we get a text of a web element?
A: Get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages.
Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();

Q: How to select value in a dropdown?
A: Value in the drop down can be selected using WebDriver’s Select class.
Syntax:
selectByValue:
Select selectByValue = newSelect(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select (driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex = newSelect(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);

Q: What are the different types of navigation commands?
A: Following are the navigation commands:
navigate().back() – The above command requires no parameters and takes back the user to the previous webpage in the web browser’s history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page with reference to the browser’s history.
Sample code:
driver.navigate().forward();
navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window and navigate to the specified URL.
Sample code:
driver.navigate().to(“https://google.com”);

Q: How to click on a hyper link using linkText?
A: driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and thus the user would be re-directed to the corresponding page.
The above mentioned link can also be accessed by using the following command.
driver.findElement(By.partialLinkText(“Goo”)).click();
The above command find the element based on the substring of the link provided in the parenthesis and thus partialLinkText() finds the web element with the specified substring and then clicks on it.

A: An inline frame acronym as iframe is used to insert another document with in the current HTML document or simply a web page into a web page by enabling nesting.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
------------

frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();

Q: When do we use findElement() and findElements()?
A: 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: How to find more than one web element in the list?
A: 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
// Storing the list
List <WebElement> elementList = driver.findElements(By.xpath("//div[@id='example']//ul//li"));
// Fetching the size of the list
int listSize = elementList.size();
for (int i=0; i<listSize; i++)
{
// Clicking on each service provider link
serviceProviderLinks.get(i).click();
// Navigating back to the previous page that stores link to service providers
driver.navigate().back();
}

Q: What is the difference between driver.close() and driver.quit command?
A: 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: Can Selenium handle windows based pop up?
A: Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using Selenium.

Q: How can we handle web based pop up?
A: 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: How can we handle windows based pop up?
A: 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: How to assert title of the web page?
A: //verify the title of the web page
assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the page”));

Q: How to mouse hover on a web element using WebDriver?
A: 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:
// Instantiating Action Interface
Actions actions=new Actions(driver);
// howering on the dropdown
actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();
// Clicking on one of the items in the list options
WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
subLinkOption.click();

Q: How to retrieve css properties of an element?
A: 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: How to capture screenshot in WebDriver?
A: import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CaptureScreenshot {
       WebDriver driver;
       @Before
       public void setUp() throws Exception {
            driver = new FirefoxDriver();
            driver.get("https://google.com");
     }
     @After
     public void tearDown() throws Exception {
            driver.quit();
     }

     @Test
     public void test() throws IOException {
            // Code to capture the screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            // Code to copy the screenshot in the desired location
FileUtils.copyFile(scrFile, new File("C:\\CaptureScreenshot\\google.jpg"));                 
     }
}

Q: What is Junit?
A: Junit is a unit testing framework introduced by Apache. Junit is based on Java.

Q: What are Junit annotations?
A: 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: What is TestNG and how is it better than Junit?
A: 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: How to set test case priority in TestNG?
A: Setting Priority in TestNG
Code Snippet
package TestNG;
import org.testng.annotations.*;
public class SettingPriority {
      @Test(priority=0)
      public void method1() {  
      }
      @Test(priority=1)
      public void method2() { 
      }
      @Test(priority=2)
      public void method3() {  
      }
}
Test Execution Sequence:
1.     Method1
2.     Method2
3.     Method3

Q: What is a framework?
A: 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: What are the advantages of Automation framework?
A: Advantage of Test Automation framework
  • Reusability of code
  • Maximum coverage
  • Recovery scenario
  • Low cost maintenance
  • Minimal manual intervention
  • Easy Reporting

Q: What are the different types of frameworks?
A: 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: How can I read test data from excels?
A: Test data can efficiently be read from excel using JXL or POI API.

Q: What is the difference between POI and jxl jar?
A:
#
JXL jar
POI jar
1
JXL supports “.xls” format i.e. binary based format. JXL doesn’t support Excel 2007 and “.xlsx” format i.e. XML based format
POI jar supports all of these formats
2
JXL API was last updated in the year 2009
POI is regularly updated and released
3
The JXL documentation is not as comprehensive as that of POI
POI has a well prepared and highly comprehensive documentation
4
JXL API doesn’t support rich text formatting
POI API supports rich text formatting
5
JXL API is faster than POI API
POI API is slower than JXL API
Q: What is the difference between Selenium and QTP?
A:
Feature
Selenium
Quick Test Professional (QTP)
Browser Compatibility
Selenium supports almost all the popular browsers like Firefox, Chrome, Safari, Internet Explorer, Opera etc
QTP supports Internet Explorer, Firefox and Chrome. QTP only supports Windows Operating System
Distribution
Selenium is distributed as an open source tool and is freely available
QTP is distributed as a licensed tool and is commercialized
Application under Test
Selenium supports testing of only web based applications
QTP supports testing of both the web based application and windows based application
Object Repository
Object Repository needs to be created as a separate entity
QTP automatically creates and maintains Object Repository
Language Support
Selenium supports multiple programming languages like Java, C#, Ruby, Python, Perl etc
QTP supports only VB Script
Vendor Support
As Selenium is a free tool, user would not get the vendor’s support in troubleshooting issues
Users can easily get the vendor’s support in case of any issue
Q: Can WebDriver test Mobile applications?
A: WebDriver cannot test Mobile applications. WebDriver is a web based testing tool, therefore applications on the mobile browsers can be tested.

Q: Can captcha be automated?
A: No, captcha and bar code reader cannot be automated.

Q: What is Object Repository? How can we create Object Repository in Selenium?
A: 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.
That’s all for now.
Hope in this article you will find answers to most frequently asked Selenium and WebDriver Interview questions. The answers provided here are also helpful for understanding the Selenium basics and advanced WebDriver topics.


Q: What is Selenium?
A: Selenium is a suite of tools for browser automation. It is composed of "IDE", a recording and playback mechanism, "WebDriver" and Remote Control "RC" which provide APIs for browser automation in a wide variety of languages, and "Grid", which allows many tests using the APIs to be run in parallel. QA Tester should not forget to mention during interview that with the release of Selenium 2, Selenium RC has been officially deprecated in favor of Selenium WebDriver. It works with most browsers, including Firefox 3.6 and the last, latest and next release of Firefox (currently Firefox 17-19); Internet Explorer 6 and up; Google Chrome; Safari 4 and 5; Android Ice Cream Sandwich and onward; and Opera 11.6+.

Q: Describe technical problems that you had with Selenium tool?
A: As with any other type of test automation tools like SilkTest, HP QTP, Canoo Webtest, Selenium allows to record, edit, and debug tests cases. However there are several problems that seriously affect maintainability of recorded test cases, occasionally Quality Assurance Engineers complain that it takes more time to maintain automated test cases than to perform manual testing; however this is an issue with all automated testing tools and most likely related to improper testing framework design. Another problem is complex ID for an HTML element. If IDs is auto-generated, the recorder test cases may fail during playback. The work around is to use XPath to find required HTML element. Selenium supports AJAX without problems, but QA Tester should be aware that Selenium does not know when AJAX action is completed, so ClickAndWait will not work. Instead QA tester could use pause, but the snowballing effect of several 'pause' commands would really slow down total testing time of test cases. The best solution would be to use waitForElement.

Q: What test can Selenium do?
A: Selenium could be used for the functional, regression, load testing of the web based applications. The automation tool could be implemented for post release validation with continuous integration tools like Jenkins, Hudson, QuickBuild or CruiseControl.

Q: What is the price of Selenium license per server?
A: Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without charge.

Q: How much does Selenium license cost per client machine?
A: Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without charge.

Q: Where to download Selenium?
A: Selenium can be downloaded and installed for free from <a href="http://seleniumhq.org/" target="_blank">seleniumhq.org</a>

Q: What is the latest version of Selenium components?
A: The latest versions are Selenium IDE 2.5.0, Selenium Server (formerly the Selenium RC Server) 2.42.2, The Internet Explorer Driver Server 2.42.2, Selenium Client Drivers Java 2.42.2, Selenium Client Drivers C# 2.42.0, Selenium Client Drivers Ruby 2.42.0, Selenium Client Drivers Python 2.42.1, Selenium Client Drivers Javascript (Node) 2.42.0

Q: What is Selenium IDE?
A: Selenium IDE is a Firefox add-on that records clicks, typing, and other actions to make a test cases, which QA Tester can play back in the Firefox browser or export to Selenium RC.  Selenium IDE has the following features: record/play feature, debugging with step-by-step and breakpoints, page abstraction functionality, an extensibility capability allowing the use of add-ons or user extensions that expand the functionality of Selenium IDE.

Q: What are the limitations of Selenium IDE?
A: Selenium IDE has many great features and is a fruitful and well-organized test automation tool for developing test cases, in the same time Selenium IDE is missing certain vital features of a testing tool: conditional statements, loops, logging functionality, exception handling, reporting functionality, database testing, re-execution of failed tests and screenshots taking capability. Selenium IDE doesn't for IE, Safari and Opera browsers.

Q: What does SIDE stand for?
A: Selenium IDE. It was a very tricky interview question.

Q: What is Selenium Remote Control (RC) tool?
A: Selenium Remote Control (RC) is the powerful solution for test cases that need more than simple browser actions and linear execution. Selenium-RC allows the developing of complex test scenarios like reading and writing files, querying a database, and emailing test reports. These tasks can be achieved by tweaking test cases in your preferred programming language. Selenium RC has been officially deprecated in favor of Selenium WebDriver.

Q: What are the advantages using Selenium as testing tool?
A: If QA Tester would compare Selenium with HP QTP or Micro Focus SilkTest, QA Engineer would easily notice tremendous cost savings for Selenium. In contrast to expensive SilkTest license or QTP license, Selenium automation tool is absolutely free. It means that with almost no investment in purchasing tools, QA Team could easily build the state of the art test automation infrastructure. Selenium allows developing and executing test cases in various programming languages including .NET, Java, Perl, RubyPython, PHP and even HTML. This is a great Selenium advantage, most likely your software developers already know how to develop and maintain C# or Java code, so they transfer coding techniques and best practices to QA team. Selenium allows simple and powerful DOM-level testing and in the same time could be used for testing in the traditional waterfall or modern Agile environments. Selenium would be definitely a great fit for the continuous integration tools Jenkins, Hudson, CruiseControl, because it could be installed on the server testing box, and controlled remotely from continuous integration build.

Q: What is Selenium Grid?
A: Selenium Grid extends Selenium RC to distribute your tests across multiple servers, saving you time by running tests in parallel.

Q: What is Selenium WebDriver?
A: Selenium WebDriver is a tool for writing automated tests of websites. It  is an API name and aims to mimic the behavior of a real user, and as such interacts with the HTML of the application. Selenium WebDriver is the successor of Selenium Remote Control which has been officially deprecated.

Q: How many browsers are supported by Selenium IDE?
A: Test Engineer can record and playback test with Selenium IDE in Firefox.

Q: Can Selenium test an application on iPhone's Mobile Safari browser?
A: Selenium should be able to handle Mobile Safari browser. There is experimental Selenium IPhone Driver for running tests on Mobile Safari on the iPhone, iPad and iPod Touch.

Q: Can Selenium test an application on Android browser?
A: Selenium should be able to handle Android browser. There is experimental Selenium Android Driver for running tests in Android browser.

Q: What are the disadvantages of using Selenium as testing tool?
A: Selenium weak points are tricky setup; dreary errors diagnosis; tests only web applications

Q: How many browsers are supported by Selenium Remote Control?
A: QA Engineer can use Chrome, Firefox, IE, Safari and Opera browsers to run actual tests in Selenium RC.

Q: How many programming languages can you use in Selenium RC?
A: Several programming languages are supported by Selenium Remote Control - C# Java Perl PHP Python Ruby

Q: How many testing framework can QA Tester use in Selenium RC?
A: Testing frameworks aren't required, but they can be helpful if QA Tester wants to automate test cases. Selenium RC supports Bromine, JUnit, NUnit, RSpec (Ruby), Test::Unit (Ruby), TestNG (Java), unittest (Python).

Q: How to developer Selenium Test Cases?
A: Using the Selenium IDE, QA Tester can record a test to comprehend the syntax of Selenium IDE commands, or to check the basic syntax for a specific type of user interface. Keep in mind that Selenium IDE recorder is not clever as QA Testers want it to be. Quality assurance team should never consider Selenium IDE as a "record, save, and run it" tool, all the time anticipate reworking a recorded test cases to make them maintainable in the future.

Q: What programming language is best for writing Selenium tests?
A: The web applications may be written in Java, Ruby, PHP, Python or any other web framework. There are certain advantages for using the same language for writing test cases as application under test. For example, if the team already have the experience with Java, QA Tester could always get the piece of advice while mastering Selenium test cases in Java. Sometimes it is better to choose simpler programming language that will ultimately deliver better success. In this case QA testers can adopt easier programming languages, for example Ruby, much faster comparing with Java, and can become become experts as soon as possible.

Q: Have you read any good books on Selenium?
A: There are several great books covering Selenium automation tool, you could check the review.

Q: Do you know any alternative test automation tools for Selenium?
A: Selenium appears to be the mainstream open source tool for browser side testing, but there are many alternatives. Canoo Webtest is a great Selenium alternative and it is probably the fastest automation tool. Another Selenium alternative is Watir, but in order to use Watir QA Tester has to learn Ruby. One more alternative to Selenium is Sahi, but is has confusing interface and small developers community.

Q: Compare HP QTP vs Selenium?
A: When QA team considers acquiring test automation to assist in testing, one of the most critical decisions is what technologies or tools to use to automate the testing. The most obvious approach will be to look to the software market and evaluate a few test automation tools.

Q: How can I learn to automate testing using Selenium?
A: Don't be surprised if the interviewer asks you to describe the approach for learning Selenium.  This interviewer wants to hear how you can innovative software test automation process the company.  Most likely they are looking for software professional with a good Selenium experience,  who can do Selenium training for team members and get the team started with test automation.

Q: Is Selenium IDE a good choice for automated testing?
A: Even QA Testers, who only started to work with Selenium, know that Selenium IDE is an integrated development environment for Selenium scripts implemented as a Firefox extension. It helps to perform some automated functional browser testing and allows QA Tester to record, edit, and debug tests. Selenium IDE is a great tool for simple test cases and not that suitable for complex scenarios, where it would be better to use Selenium Webdriver. In the same time IDE could be used for trivial automation testing, to repeat some routine and lightweight tasks that let your web application ready to be tested.


Q: What is Selenium?
A: Selenium is a browser automation tool which lets you automated operations like -type, click, and selection from a drop down of a web page.

Q: How is Selenium different from commercial browser automation tools?
A: Selenium is a library which is available in a gamut of languages i.e. java, C#, python, ruby, php etc while most commercial tools are limited in their capabilities of being able to use just one language. More over many of those tools have their own proprietary language which is of little use outside the domain of those tools. Most commercial tools focus on record and replay while Selenium emphasis on using Selenium IDE (Selenium record and replay) tool only to get acquainted with Selenium working and then move on to more mature Selenium libraries like Remote control (Selenium 1.0) and Web Driver (Selenium 2.0).
Though most commercial tools have built in capabilities of test reporting, error recovery mechanisms and Selenium does not provide any such features by default. But given the rich set of languages available with Selenium it very easy to emulate such features.

Q: What are the set of tools available with Selenium?
A: Selenium has four set of tools -Selenium IDE, Selenium 1.0 (Selenium RC), Selenium 2.0 (WebDriver) and Selenium Grid. Selenium Core is another tool but since it is available as part of Selenium IDE as well as Selenium 1.0, it is not used in isolation.

Q: Which Selenium Tool should I use?
A: It entirely boils down to where you stand today in terms of using Selenium. If you are entirely new to Selenium then you should begin with Selenium IDE to learn Selenium location strategies and then move to Selenium 2 as it is the most stable Selenium library and future of Selenium. Use Selenium Grid when you want to distribute your test across multiple devices. If you are already using Selenium 1.0 than you should begin to migrate your test scripts to Selenium 2.0

Q: What is Selenium IDE?
A: Selenium IDE is a firefox plug-in which is (by and large) used to record and replay test is firefox browser. Selenium IDE can be used only with firefox browser.

Q: Which language is used in Selenium IDE?
A: Selenium IDE uses html sort of language called Selenese. Though other languages (java, c#, php etc) cannot be used with Selenium IDE, Selenium IDE lets you convert test in these languages so that they could be used with Selenium 1.0 or Selenium 2.0

Q: What is Selenium 1.0?
A: Selenium 1.0 or Selenium Remote Control (popularly known as Selenium RC) is library available in wide variety of languages. The primary reason of advent of Selenium RC was incapability of Selenium IDE to execute tests in browser other than Selenium IDE and the programmatical limitations of language Selenese used in Selenium IDE.

Q: What is Selenium 2.0?
A: Selenium 2.0 also known as WebDriver is the latest offering of Selenium. It provides better API than Selenium 1.0 does not suffer from java script security restriction which Selenium 1.0 doessupports more UI complicated UI operations like drag and drop

Q: What are the element locators available with Selenium which could be used to locate elements on web page?
A: There are mainly 4 locators used with Selenium:
html id
html name
XPath locator and
Css locators

Q: What is Selenium Grid?
A: Selenium grid lets you distribute your tests on multiple machines and all of them at the same time. Hence you can execute test on IE on Windows and Safari on Mac machine using the same test script (well, almost always). This greatly helps in reducing the time of test execution and provides quick feedback to stack holders.

Selenium IDE Questions

Q: What are two modes of views in Selenium IDE?
A: Selenium IDE can be opened either in side bar (View > Side bar > Selenium IDE) or as a pop up window (Tools > Selenium IDE). While using Selenium IDE in browser side bar it cannot record user operations in a pop up window opened by application.

Q: Can I control the speed and pause test execution in Selenium IDE?
A: Selenium IDE provides a slider with Slow and Fast pointers to control the speed of execution.

Q: Where do I see the results of Test Execution in Selenium IDE?
A: Result of test execution can be views in log window in Selenium IDE:

Q: Where do I see the description of commands used in Selenium IDE?
A: Commands of description can be seen in Reference section:

Q: Can I build test suite using Selenium IDE?
A: Yes, you can first record individual test cases and then group all of them in a test suite. Following this entire test suite could be executed instead of executing individual tests.

Q: What verification points are available with Selenium?
A: There are largely three type of verification points available with Selenium:
Check for page title
Check for certain text
Check for certain element (text box, drop down, table etc)

Q: I see two types of check with Selenium -verification and assertion, what's the difference between tow?
A: A verification check lets test execution continue even in the wake of failure with check, while assertion stops the test execution. Consider an example of checking text on page, you may like to use verification point and let test execution continue even if text is not present. But for a login page, you would like to add assertion for presence of text box login as it does not make sense continuing with test execution if login text box is not present.

Q: I don't see check points added to my tests while using Selenium IDE, how do I get them added to my tests?
A: You need to use context menu to add check points to your Selenium IDE tests:

Q: How do I edit tests in Selenium IDE?
A: There are two ways to edit tests in Selenium IDE; one is the table view while other looking into the source code of recorded commands:

Q: What is syntax of command used in Selenium?
A: There are three entities associated with a command:
Name of Command
Element Locator (also known as Target)
Value (required when using echo, wait etc)

Q: There are tons of Selenium Command, am I going to use all of them
A: This entirely boils down to operations you are carrying out with Selenium. Though you would definitely be using following Selenium Commands more often:
Open: opens a web page.
click/clickAndWait: click on an element and waits for a new page to load.
Select: Selects a value from a drop down value.
verifyTitle/assertTitle: verifies/asserts page title.
verify/assert ElementPresent: verifies/asserts presence of element, in the page.
verify/assert TextPresent verifies/asserts  expected text is somewhere on the page.

Q: How do I use html id and name while using Selenium IDE
A: Html id and name can be used as it is in selenium IDE. For example Google search box has name -"q" and id -"list-b" and they can be used as target in selenium IDE:

Q: What is XPath? When would I have to use XPath in Selenium IDE?
A: XPath is a way to navigate in xml document and this can be used to identify elements in a web page. You may have to use XPath when there is no name/id associated with element on page or only partial part of name/ide is constant.
Direct child is denoted with - /
Relative child is denoted with - //
Id, class, names can also be used with XPath:

//input[@name='q']
//input[@id='lst-ib']
//input[@class=' lst']
If only part of id/name/class is constant than "contains" can be used as:
//input[contains(@id,'lst-ib')]

Q: What is CSS location strategy in Selenium?
A: CSS location strategy can be used with Selenium to locate elements, it works using cascade style sheet location methods in which -
Direct child is denoted with -(a space)
Relative child is denoted with ->
Id, class, names can also be used with XPath:

css=input[name='q']
css=input[id='lst-ib'] or input#lst-ib
css=input[class=' lst'] or input.lst
If only part of id/name/class is constant than "contains" can be used as:
css=input[id*=' lst-ib ')]
Element location strategy using inner text
css = a:contains('log out')

Q: There is id, name, XPath, CSS locator, which one should I use?
A: If there are constant name/id available than they should be used instead of XPath and CSS locators. If not then css locators should be given preference as their evaluation is faster than XPath in most modern browsers.

Q:  I want to generate random numbers, dates as my test data, how do I do this in Selenium IDE?
A: This can be achieved by executing java script in Selenium. Java script can be executed using following syntax:
             type
             css=input#s
             javascript{Math.random()}
And for date:
             type
             css=input#s
             javascript{new Date()}

Q: Can I store result of an evaluation and use it later in my test?
A: You can use "store" command to achieve this. You can save result of an evaluation in a variable and use it later in your Selenium IDE script. For example we can store value from a text box as following, and later use it to type it in another text box:
            storeText
            css=input#s
            var1
            type
            css=input#d
            ${var1}

Q: I have stored result of an evaluation; can I print it in IDE to check its value?
A: You can use echo command as following to check the stored value in Selenium IDE:
             storeText
             css=input#s
             var1
             echo
             ${var1}

Q: Can I handle java script alert using Selenium?
A: You could use verify/assertAlert to check presence of alert on page. Since selenium cannot click on "Ok" button on js alert window, the alert itself does not appear on page when this check is carried out.

Q: Selenium has recorded my test using XPath, how do I change them to css locator?
A: You can use drop down available next to Find in Selenium to change element locator used by Selenium:

Q: I have written my own element locator, how do I test it?
A: You can use Find button of Selenium IDE to test your locator. Once you click on it, you would see element being highlighted on screen provided your element locator is right Else one error message would be displayed in log window.

Q: I have written one js extension; can I plug it in Selenium and use it?
A: You could specify you js extension in "Options" window of Selenium IDE:


Q: How do I convert my Selenium IDE tests from Selenese to another language?
A: You could use Format option of Selenium IDE to convert tests in another programming language:
I have converted my Selenium IDE tests to java but I am not able to execute them, execution options as well as Table tab of Selenium IDE is disabledL
This is because Selenium IDE does not support execution of test in any other language than Selenese (language of Selenium IDE). You can convert Selenium IDE in a language of your choice and then use Selenium 1.0 to execute these tests in that language.

Q: I want to use only Selenese as my test script language but still want to execute tests in other browsers, how do I do that?
A: You can execute you Selenese test in another browser by specifying the "-htmlSuite" followed by path of your Selenese suite while starting the Selenium Server. Selenium Server would be covered in details in question about Selenium RC.

Q: I have added one command in middle of list of commands, how do I test only this new command?
A: You can double click on newly added command and Selenium IDE would execute only that command in browser.

Q: Can I make Selenium IDE tests begin test execution from a certain command and not from the very first command?
A: You could set a command as "start" command from context menu. When a command is set as start command then a small green symbol appears before command. Same context menu can be used to toggle this optio

Q: Are there other tools available outside Selenium IDE to help me tests my element locators
A: You could XPath checker - to test you XPath locators and Firefinder (a firebug add on) to test you css locators:
Firefinder can also be used to test XPath locators.

Q: What is upcoming advancement in Selenium IDE?
A: The latest advancement in Selenium IDE would be to have capabilities of converting Selenium IDE tests in Webdriver (Selenium 2.0) options. This would help generating quick and dirty tests for Selenium 2.0

Q: How can I use looping option (flow control) is Selenium IDE
A: Selenese does not provide support for looping, but there is extension which could be used to achieve same. This extension can be download from here -
This extension can be added under "Selenium IDE Extension" section to use loop feature in Selenium IDE.

Q: Can I use screen coordinate while using click command? I want to click at specific part of my element.
A: You would need to use clickAT command to achieve. clickAt command accepts element locator and x, y coordinates as arguments:
clickAt(locator, coordString)

Q: How do I verify presence of drop down options using Selenium?
A: Use assertSelectOptions as following to check options in a drop down list:
assertSelectOptions<elementlocator>

Q: Can I get data from a specific html table cell using Selenium IDE?
A: Use storeTable command to get data from a specific cell in an html table, following example store text from cell 0,4 from an html table:
             storeTable
             css=#tableId.0.4
             textFromCell

Q: I want to make Selenium IDE record and display css locator followed by other locators, is it possible to give high priority to css locator in Selenium IDE?
A: You can change default behavior of Selenium IDE > element locator preference by crating js file with following:
LocatorBuilders.order = ['css:name', 'css:id', 'id', 'link', 'name', 'xpath:attributes'];
And add this file under "Selenium IDE Extension" under Selenium Options.

Q: My application has dynamic alerts which don't always appear, how do I handle them?
A: If you want to simulate clicking "ok " on alert than use -chooseOkOnNextConfirmation and if you want to simulate clicking "cancel" on alert than use - chooseCancelOnNextConfirmation ( )

Q: Can I right click on a locator?
A: You can use command - contextMenu ( locator) to simulate right click on an element in web page.

Q: How do I capture screen shot of page using Selenium IDE?
A: Use command -captureEntirePageScreenshot to take screen shot of page.


Q: I want to pause my test execution after certain command.
A: Use pause command which takes time in milliseconds and would pause test execution for specified time -pause ( waitTime )

Q: I used open command to launch my page, but I encountered time out error
A: This happens because open commands waits for only 30 seconds for page to load. If you application takes more than 30 sec then you can use "setTimeout ( timeout )" to make selenium IDE wait for specified time, before proceeding with test execution.

Q: What's the difference between type and typeKeys commands?
A: type command simulates enter operations at one go while typeKeys simulates keystroke key by key.
typeKeys could be used when typing data in text box which bring options (like Google suggestion list) because such operation are not usually simulated using type command.


Selenium RC (Selenium 1.0) Questions


Q: What is Selenium RC (also known as Selenium 1.0)?
A: Selenium RC is an offering from SeleniumHQ which tries to overcome following draw backs of Selenium IDE:
Able to execute tests only with Firefox
Not able to use full-fledged programming language and being limited to Selenese

Q: What are the main components of Selenium RC?
A: Selenium RC has two primary components:
Client libraries which let you writes tests in language of your preference i.e. java, C#, perl, php etc
Selenium sever which acts as a proxy between browser and application under test (aut)

Q: Why do I need Selenium Server?
A: Selenium uses java script to drives tests on a browser; Selenium injects its own js to the response which is returned from aut. But there is a java script security restriction (same origin policy) which lets you modify html of page using js only if js also originates from the same domain as html. This security restriction is of utmost important but spoils the working of Selenium. This is where Selenium server comes to play an important role.
Selenium server stands between aut and browser and injects selenium js to the response received from aut and then it is delivered to broswer. Hence browser believes that entire response was delivered from aut.

Q: What is Selenium core? I have never used it!!!
A: Selenium core is the core js engine of Selenium which executes tests on browser, but because of same origin policy it needs to be deployed on app server itself, which is not always feasible. Hence Selenium core is not used in isolation. Selenium IDE as well as Selenium RC use Selenium core to drive tests while over coming same origin policy. In case of Selenium IDE tests are run in context of browser hence it is not hindered by same origin policy and with Selenium RC, Selenium Server over comes same origin policy.


Q: Where is executable for Selenium RC, how do I install it?
A: Installation is a misnomer for Selenium RC. You don't install Selenium RC you only add client libraries to you project. For example in case of java you add client driver and Selenium server jars in Eclipse or IntelliJ which are java editors.

Q: I have downloaded Selenium Server and Client libraries, how do I start Selenium Server?
A: To start Selenium Server, you need to navigate to installation directory of Selenium server and execute following command:
                Java -jar <selenium-server>.jar</selenium-server>
This will start Selenium server at port 4444 by default.
Notice that you need to have java version 1.5 or higher available on your system to be able to use Selenium server.

Q: On my machine port 4444 is not free . How do Use another port?
A: You can specify port while running the selenium server as:
                Java -jar <selenium-server>.jar:port 5555</selenium-server>
               
Q: I am new to programming; can Selenium generate sample code from my Selenese scripts?
A: You can first record tests in Selenium IDE and then use format option to convert them in a language of your choice.

Q: Can I start Selenium server from my program instead of command line
A: If you are using java then you can start Selenium server using SeleniumServer class. For this you need to instantiate SeleniumServer and then call start() method on it.
                seleniumServer = new SeleniumServer();
                seleniumServer.start();

Q: And how do I start the browser?
A: While using java you need to create instance of DefaultSelenium class and pass it four parameters:
selenium = new DefaultSelenium(serverHost, serverPort, browser, appURL);
selenium.start();

Herein you need to pass,
host where Selenium server is running,
port of Selenium server,
browser where tests are to be executed and
application URL

Q: I am not using java to program my tests, do I still have to install java on my system?
A: Yes, since Selenium server is written in java you need java to be installed on your system to be able to use it. Even though you might not be using java to program your tests.

Q: What are the browsers offering from Selenium?
A: Following browsers could be used with Selenium:
  *firefox
  *firefoxproxy
  *pifirefox
  *chrome
  *iexploreproxy
  *iexplore
  *firefox3
  *safariproxy
  *googlechrome
  *konqueror
  *firefox2
  *safari
  *piiexplore
  *firefoxchrome
  *opera
  *iehta
  *custom
Here pi and proxy stand for proxy injection mode of Selenium server

Q: During execution of tests I see two browser windows; one my test application another window shows commands being executed. Can I limit it to just one window?
A: Yes you can instruct Selenium Server to launch just one window. To do so you must specify:singleWindow while starting the Selenium server as:
            Java -jar <selenium-server>.jar:singleWindow</selenium-server>


Q: My tests usually time out. Can I specify bigger time out?
A: This usually happens while using open method with Selenium. One way to overcome this is to use setTimeOut method in your test script another way is to specify time out while starting Selenium server as following:
            Java -jar <selenium-server>.jar:timeout<time in="" seconds=""></time></selenium-server>


Q: My system is behind corporate network, how do I specify my corporate proxy?
A: You can specify your corporate proxy as following while starting Selenium Server:
 java -jar <selenium-server>.jar -Dhttp.proxyHost=<your proxy="" server=""> -Dhttp.proxyPort=<your port=""> -Dhttp.proxyUser=<your name=""> -Dhttp.proxyPassword=<your password=""></your></your></your></your></selenium-server>

Q: I am switching domains in my test scripts. I move from "yahoo.com" to "google.com" and my tests encounter permission denied error
A: Changing domains is also a security restriction from java script. To overcome this you should start you Selenium server in proxy injection mode as:
java -jar <selenium-server>.jar:proxyInjectionMode</selenium-server>
Now Selenium server would act as proxy server for all the content going to test application

Q: Can I execute my Selenese tests in another browser using Selenium server? I want to use only Selenese script my tests but still want to execute my test in non firefox browsers
A: Yes you can. To do so you need to specify following parameters while starting Selenium server:
Browser
Test domain
Path to html suite (you Selenese tests) and
Path to result
java -jar <>.jar -htmlSuite <browser> <app url="">  <test path="" result=""></test></app></browser>

Q: Can I log more options during test execution?
A: If you want to log browser side option during test execution then you should start Selenium server as following:
java -jar <>.jar:browserSideLog

Q: Can I use Selenium RC on my UNIX/Mac also?
A: You can use Selenium RC on any system which is capable I running Java. Hence you can use it on RC and UNIX machines also

Q: I want to test my scripts on new experimental browser, how do I do that?
A: You can specify *custom followed by path to browser to execute your tests on any browser while starting Selenium server
        *custom <path browser="" to=""></path>

Q: I executed my tests cases but where is the test report?
A: Selenium RC itself does not provide any mechanism for test reporting. Test reporting is driven from the framework you use for Selenium. For example with java client driver of Selenium:
if you are using JUnit then you can use ant plug-in of JUnit to generate test report
if you are using TestNG then TestNG generates reports for you
Same reporting option is available with PHP unit and other client libraries you are using.

Q: How do I use recovery scenarios with Selenium? I used to use them with QTP.
A: Power of recovery scenarios lies with the programming language you use. If you are using java then you can use Exception handling to overcome same. For example if you are reading data from a file and file is not available then you should keep you code statements in "try catch" block so that test execution could continue even in the wake of errors. Such mechanism entirely boils down the errors you want to recover from, while being able to continue with test execution.

Q: How do I iterate through options in my test script.
A: You can use loop features of the programming language, for example you can use "for" loop in java as following to type different test data in a text box:
     // test data collection in an array
     String[] testData = {"test1", "test2", "test3"};
   
     // iterate through each test data
     for (String s : testData) {
              selenium.type("elementLocator", testData);    
     }

Q: Can I execute java script from my tests? I want to count number of images on my page.
A: You can use method getEval() to evaluate java script. For example if you want to count number of images then you can pass following dom statement to getEval() as following:
                selenium.getEval("window.document.images.length;");
                Or to get All anchor objects from a page
                selenium.getEval("window.document.getElementsByTagName('a');");

Q: Is there a way for me to know all available options when I start Selenium Server?
A: If you want to see all options available while starting Selenium server then you should use option "-h" while starting Selenium server -
            Java:jar <selenium-server>.jar:h</selenium-server>
It would display you all the options which you can use while starting the Selenium server.

Q: I have created my own firefox profile; can I execute my test scripts on it
A: You may like to create your own firefox profile because Selenium always created a clean firefox profile while executing the tests and none of your FF settings and plug-in are considered with this clean profile. If you want to execute tests on FF with your settings then you should create custom profile for FF.
To be able to execute tests on a custom firefox profile you should specify its path while starting Selenium server. For example if your new profile is stored at "awesome location" in your directory then you should start Selenium server as following:
Java:jar <selenium-server>.jar -firefoxProfileTemplate   "awesome location"</selenium-server>

Q: How do I capture server side log from Selenium server?
A: Start your Selenium Server as following:
java -jar <selenium-server>.jar -log selenium.log</selenium-server>
And Selenium would start logging server side info, i.e.

20:44:25 DEBUG [12] org.openqa.selenium.server.SeleniumDriverResourceHandler -
Browser 12345/:top frame1 posted START NEW

Q: What are Heightened Privileges Browsers?
A: Firefox and IE have browser modes which are not restricted by java script's same origin policy. These browsers are known as browsers with elevated security privileges. In case of Firefox it is known as chrome (It's not the Google browser) and in case of IE it is known as iehta

Q: My application has lots of pop up window, how do I work with them?
A: You need to know the Window ID of pop window to be able to work with them.
First you need to bring control on pop up window; execute selenium commands there, close the pop up window and then bring control back to main window. Consider following example where click on an image brings a pop up window:
                                // click on image brings pop up window
                                selenium.click("css=img");
                                // wait for pop up window identified using anchor target "ss"
          selenium.waitForPopUp("ss", getWaitPeriod());
          selenium.selectWindow("ss");
        
          // Some more operations on popup window

                                // Close the pop up window and Select the main application window   
          // Main window is selected by adding null as argument
          selenium.close();
          selenium.selectWindow("null");
          // continue with usual operation <span style="color: black; font-family: Wingdings; font-size: 12pt;">J

Q: While trying to execute my tests with firefox I encountered following error -"Firefox Refused Shutdown While Preparing a Profile". How do I solve it?
A: This message simply means that Selenium is not able to launch FF browser as it is already running on your system. To overcome this you should close all running instances of FF browser.
You should also check your system process if there is any hidden FF profile running which is not visible on screen. You should kill all FF processes and following this your tests should run smooth

Q: While trying to execute my tests with firefox I encountered following error -"Firefox Refused Shutdown While Preparing a Profile". How do I solve it?
A: This message simply means that Selenium is not able to launch FF browser as it is already running on your system. To overcome this you should close all running instances of FF browser.
You should also check your system process if there is any hidden FF profile running which is not visible on screen. You should kill all FF processes and following this your tests should run smooth

Q: My application uses Ajax heavily how do I use Selenium RC to work with Ajax operations?
A: Ajax operations don't reload a page like normal form submission but they make http requests behind the scene. You cannot use waitForPageToLoad for such operations and instead should use conditional wait for change in state of application. This could as well mean waiting for presence of an element before continuing with test operations. Consider following example in which type operation triggers Ajax operation which is followed by conditional wait for presence of a text box:
                // type operation brings element "q" on screen without loading the page
                selenium.type("elementLocator", "testData");

                // conditional wait for element "q"
                for (int second = 0;; second++) {
                                 if (second >= 60) fail("timeout");

                try { if (selenium.isElementPresent("q")) break; } catch (Exception e) {}
                                                  Thread.sleep(1000);
                }

Q: How do I upload a file using Selenium? I need to upload a word file during test execution.
A: If you are using Firefox then you can use "type" command to type in a File Input box of upload file. But type operation does not work with IE and you would have to use "Robot" class in java to work make file upload work.

Q: Why do I get "permission denied" error during execution of Selenium tests?
A: The primary reason of permission denied error is same origin policy restriction from java script. To overcome this error you can use browsers with elevated security privileges. In case of Firefox you should use *chrome and in case of IE you should use *iehta as browser for working with Selenium.

Q: I am not able to use "style" attribute to locate element with IE browser
A: This is because IE expects attribute values to be in caps while other browsers expect it to be lower case letters. Hence

//tr[@style="background-color:yellow"] works with other browsers
//tr[@style="BACKGROUND-COLOUR:yellow"] works with IE

Q: Are there any technical limitations while using Selenium RC?
A: Besides notorious "same origin policy" restriction from js, Selenium is also restricted from exercising anything which is outside browser. For example you cannot click on "Tools" option of your browser by just using Selenium.

Q: But my tests need me to exercise objects outside browser, how do I achieve it?
A: You can use Robot class in java to achieve this, but it would be dirty solution even if you get through this.

Q: Does Selenium have any offering for mobile browsers?
A: Selenium 2.0 (WebDriver) provides iPhone as well Android drivers which could be used to drive tests on mobile browsers

Q: How does Selenium RC stand with other commercial tools?
A: The biggest advantage of Selenium RC is that it is absolutely free and has vast support of languages and browsers (almost always). Selenium lags when it comes to test reporting as Selenium does not have any in built reporting but this can be easily achieved using the programming language you decide to work on with Selenium. A bigger drawback is not being able to exercise objects which are outside browser window, for example clicking on folder on your desktop.

Q: How does Selenium RC stand with other commercial tools?
A: The biggest advantage of Selenium RC is that it is absolutely free and has vast support of languages and browsers (almost always). Selenium lags when it comes to test reporting as Selenium does not have any in built reporting but this can be easily achieved

Q: Can I just use Selenium RC to drive tests on two different browsers on one operating system without using Selenium Grid?
A: If you are using java client driver of Selenium then java testing framework TestNG lets you achieve this. You can set tests to be executed in parallel using "parallel=test" attribute and define two different tests, each using a different browser. Whole set up would look as  (notice the highlighted sections for browser in test suite):

<xml version="1.0" encoding="utf-8"?>
<! DOCTYPE suite <span style="color: grey;">SYSTEM <span style="color: #3f7f5f;">"http://testng.org/testng-1.0.dtd" >

<suitename="Test Automation"verbose="10">
     <parametername="serverHost"value="localhost" />
     <parametername="appURL"value="http://tamil.yahoo.com"/>
     <parametername="proxyInjection"value="false" />
     <parametername="serverPort"value="4444"/>
   
     <testname="Web Test1">
          <parametername=<span style="color: #2a00ff;">"browser"value=<span style="color: #2a00ff;">"*chrome" />
          <parametername="m"value="1">parameter>

<classes><classname="com.core.tests.TestClass1">class>classes>
     test> 
   
     <testname="Web Test2">
          <parametername=<span style="color: #2a00ff;">"browser"value=<span style="color: #2a00ff;">"*iehta" />
          <parametername="m"value="2">parameter>

<classes><classname="com.core.tests.TestClass1">class>classes>
     test>
   
<span style="color: teal; font-family: 'Courier New'; font-size: 12pt; line-height: 18px;"><span style="background-attachment: scroll; background-color: silver; background-image: none; background-position: 0% 0%; color: #3f7f7f; font-family: 'Courier New'; font-size: 12pt; line-height: 18px;">suite<span style="color: teal; font-family: 'Courier New'; font-size: 12pt; line-height: 18px;">>




Selenium Grid Questions

Q: How do I cut down text execution time for my selenium tests? I want to execute my tests on a combination of different machines and browsers.
A: Selenium grid is your friend. Selenium grid lets you distribute tests across browsers and machines of your choice.

Q: How does Selenium grid works?
A: Selenium grid uses combination of Selenium RC servers to execute tests in multiple browsers on different machine. Herein one Selenium RC server works as hub while other RC servers work as slaves, which could be controlled by hub. Whenever there is a request for a specific configuration for test execution then hub looks for a free RC slave server and if available then test execution begins on it. Once test execution is over then RC slave server would be available for next set of test execution.

Q: Can you show me one diagram which describes functionality of Selenium grid?
A: In the following diagram Selenium hub is controlling three Selenium RC servers which are running for configurations:

IE on Windows
FF on Linux
FF on windows

Q: Which jar files are needed to works with Selenium GRID?
A: You need to download and add following jar files to your Selenium set up to be able to work with Selenium. These jar files are:
selenium-grid-remote-control-standalone-<version-number>.jar</version-number>
selenium-grid-hub-standalone-<version-number>.jar</version-number>
selenium-grid-tools-standalone-<version-number>.jar</version-number>

Q: How do I start Selenium Grid hub from my machine?
A: You should have "ant" set up on your system to be able to work with Grid. Once you have downloaded Selenium Grid, navigate to its distribution directory and execute following command -
ant launch-hub
This would start grid hub on port 4444 locally. You can verify this by navigating to following URL - http://localhost:4444/console

Q: How do I start Selenium Grid Slave Server from my system?
A: Navigate to download directory of Selenium gird and execute following command:
            ant launch-remote-control
This would launch remote control server at port 555. At this point if you navigate to http://localhost:4444/console then you would see this remote control listed under "Available Remote Controls"

Q: How do I start Selenium grid slave on a different port than 5555?
A: You can use option "-Dport" followed by port number to start grid slave on a specific port.
ant -Dport=1111 launch-remote-control
ant -Dport=2222 launch-remote-control

Q: How do I start grid RC slaves on a different system than my local host so than hub could control and contact a specific configuration?
A: You should specify following configuration while starting RC slave:
                                ant -Dport=<port> -Dhost=<hostname> -DhubURL=<hub url=""> launch-remote-control</hub></hostname></port>
Herein "hostname" is the host where RC slave is running and "hub url" is URL of machine where grid hub is running.

Q: How do I specify an environment while starting grid slave machine?
A: You could specify an environment using "-Denvironment" while starting a slave machine.
                ant -Denvironment="Safari on Mac" launch-remote-control
Herein Safari on Mac is the environment which would be used to recognize configuration of RC slave.

Q: How do I use machine specific configuration in my Selenium tests?
A: You could specify machine specific configuration while instantiating Selenium as:
Selenium = new DefaultSelenium("localhost", 4444, **'Safari on Mac'**, 'http://yahoo.com');
And then you use this selenium instance to carryout operation on your web application.

Q: But how does my tests know that 'Safari on Mac' mean a safari browser? How does mapping between names like 'Safari on Mac' and original browser options available in Selenium work?
A: Selenium grid uses a file called "grid_configuration.yml" which defines configurations of all browsers. You would have to add this in your project. This file looks like:

Q: How does Selenium grid hub keeps in touch with RC slave machine?
A: Selenium grid hub keeps polling all RC slaves at predefined time to make sure they are available for testing. If not then Selenium hub disconnect any unavailable RC slaves and makes it clear that any RC slave is not available for testing. The deciding parameter is called -"remoteControlPollingIntervalInSeconds" and is defined in "grid_configuration.yml" file.

Q: My RC becomes unresponsive at times and my Selenium grid hub keeps waiting for RC slave to respond. How do I let hub know to give up on RC slave after a certain time?
A: You could state Selenium grid hub to wait for RC slave for a predefined time, and if RC slave does not responds with in this time then hub disconnects test execution on that slave. This parameter is called "sessionMaxIdleTimeInSeconds" and this parameter can be defined in "grid_configuration.yml" file.

Q: What if my hub goes down while Selenium RC slaves are up and running?
A: There is one heart beat mechanism from RC slave to hub which is reciprocal to mechanism used by hub to slave machines. RC slaves use a parameter called "hubPollerIntervalInSeconds" to keep track of running grid hub. This parameter can be defined while starting the hub as:
                ant -DhubPollerIntervalInSeconds=<timeout> launch-hub </timeout>
if hub does not respond within this time then RC slaves deregister themselves from hub.

Q: Can Selenium grid be used for performance testing?
A: Selenium grid is for functional testing of application across different configuration. Performance testing is usually not carried out on actual devices but on a simulated http request/response mechanism. If you want to use Selenium Grid for performance testing then you would have to invest heavily on s/w and h/w infrastructure.

Q: Are there additional logs available while working with Selenium grid?
A: You can find Selenium grid hub logs in "log/hub.log" and Remote Control logs in "log/rc-*.log" folder.

Q: There are various options available while starting a Selenium server, how do I use them with Selenium grid?
A: You can use "<code><span style="font-size: 10pt; line-height: 14px;">seleniumArgs"</code> Java property while launching the remote control and specify any of the option which you would with normal Selenium set up. For example you can run Selenium RC slave in single window mode using following command:
                                ant -DseleniumArgs="-singleWindow -debug" launch-remote-control

Q: I see duplicate entries in my hub console, same RC slave listed more than once :-O
A: This is because you are killing RC slave very ferociously. For example you if you just close the console without actually ending the process in more civil manner. To avoid this you should kill all RC slaves in more civil manner. If you encounter this error then you should restart Selenium hub and RC slaves would them register themselves to hub.

Q: How do I specify my corporate proxy while starting Selenium grid hub or slave machines?
A: You could use setting for "http.proxyHost" abd "http.proxyPort" while starting hub and remote control machines:
                ant -Dhttp.proxyHost=<your host="" proxy=""> -Dhttp.proxyPort=<your port="" proxy=""> launch-hub</your></your>
                ant -Dhttp.proxyHost=<your host="" proxy=""> -Dhttp.proxyPort=<your port="" proxy=""> launch-remote-control</your></your>

Q: How do I use Selenium Grid while using Java, .Net or Ruby
A: With java you can take advantage of parallel testing capabilities of TestNG to drive your Selenium grid tests
With .Net you can use "Gallio" to execute your tests in parallel
With Ruby you can use "DeepTest" to distribute your tests

Q: How about the test report when I use Selenium grid for test execution?
A: This entirely boils down to framework you use to write your tests. For example in case of java, TestNG reports should suffice.

Web Driver (Selenium 2.0) Questions

Q: What is Selenium 2.0? I have heard this buzz word many times.
A: Selenium 2.0 is consolidation of two web testing tools -Selenium RC and WebDriver, which claims to give best of both words -Selenium and WebDriver. Selenium 2.0 was officially released only of late.

Q: Why are two tools being combined as Selenium 2.0, what's the gain?
A: Selenium 2.0 promises to give much cleaner API then Selenium RC and at the same time not being restricted by java script Security restriction like same origin policy, which have been haunting Selenium from long. Selenium 2.0 also does not warrant you to use Selenium Server.

Q: So everyone is going to use Selenium 2.0?
A: Well no, for example if you are using Selenium Perl client driver than there is no similar offering from Selenium 2.0 and you would have to stick to Selenium 1.0 till there is similar library available for Selenium 2.0

Q: So how do I specify my browser configurations with Selenium 2.0?
A: Selenium 2.0 offers following browser/mobile configuration:
AndroidDriver,
ChromeDriver,
EventFiringWebDriver,
FirefoxDriver,
HtmlUnitDriver,
InternetExplorerDriver,
IPhoneDriver,
IPhoneSimulatorDriver,
RemoteWebDriver
And all of them have been implemented from interface WebDriver. To be able to use any of these drivers you need to instantiate their corresponding class.

Q: How is Selenium 2.0 configuration different than Selenium 1.0?
A: In case of Selenium 1.0 you need Selenium jar file pertaining to one library for example in case of java you need java client driver and also Selenium server jar file. While with Selenium 2.0 you need language binding (i.e. java, C# etc) and Selenium server jar if you are using Remote Control or Remote WebDriver.

Q: Can you show me one code example of setting Selenium 2.0?
A: Here is java example of initializing firefox driver and using Google Search engine:
protected WebDriver webDriver;

     //@BeforeClass(alwaysRun=true)
     public void startDriver(){
     <span style="color: #0000c0; font-family: 'Courier New'; font-size: 12pt; line-height: 18px;">webDriver = new FirefoxDriver();
     // Get Google search page and perform search on term "Test"
webDriver.get("http://www.google.com");
     webDriver.findElement(By.name("q")).sendKeys("Test");
     webDriver.findElement(By.name("btnG")).click();

Q: Which web driver implementation is fastest?
A: HTMLUnitDriver. Simple reason is HTMLUnitDriver does not execute tests on browser but plain http request -response which is far quick than launching a browser and executing tests. But then you may like to execute tests on a real browser than something running behind the scenes

Q: What all different element locators are available with Selenium 2.0?
A: Selenium 2.0 uses same set of locators which are used by Selenium 1.0 -id, name, css, XPath but how Selenium 2.0 accesses them is different. In case of Selenium 1.0 you don't have to specify a different method for each locator while in case of Selenium 2.0 there is a different method available to use a different element locator. Selenium 2.0 uses following method to access elements with id, name, css and XPath locator:

driver.findElement(By.id("HTMLid"));
driver.findElement(By.name("HTMLname"));
driver.findElement(By.cssSelector("cssLocator"));
driver.findElement(By.xpath("XPathLocator));

Q: How do I submit a form using Selenium?
A: You can use "submit" method on element to submit form: submit
Alternatively you can use click method on the element which does form submission.

Q: Can I simulate pressing key board keys using Selenium 2.0?
A: You can use "sendKeys" command to simulate key board keys as:

            element.sendKeys(" and some", Keys.ARROW_UP);
You can also use "sendKeys" to type in text box as:

            HTMLelement.sendKeys("testData");

Q: How do I clear content of a text box in Selenium 2.0
A: You can use "clear" method on text box element to clear its content:
            textBoxElement.clear();  

Q: How do I select a drop down value using Selenium2.0?
A: To select a drop down value, you first need to get the select element using one of element locator and then you can select element using visible text:

Select selectElement = new Select(driver.findElement(By.cssSelector("cssSelector")));
          selectElement.selectByVisibleText("India");

Q: What are offering to deal with popup windows while using Selenium 2.0?
A: You can use "switchTo" window method to switch to a window using window name. There is also one method "getWindowHandles" which could be used to find all Window handles and subsequently bring control on desired window using window handle:
webDriver.switchTo().window("windowName");

          for (String handle : driver.getWindowHandles()) {
              driver.switchTo().window(handle);
          }


Q: How about handling frames using Selenium 2.0?
A: You can use "switchTo" frame method to bring control on an HTML frame:
            driver.switchTo().frame("frameName");
You can also use index number to specify a frame:
            driver.switchTo().frame("parentFrame.4.frameName");
This would bring control on frame named -"frameName" of the 4<sup>th</sup> sub frame names "parentFrame"

Q: Can I navigate back and forth in a browser in Selenium 2.0?
A: You can use Navigate interface to go back and forth in a page. Navigate method of WebDriver interface returns instance of Navigation. Navigate interface has methods to move back, forward as well as to refresh a page:
driver.navigate().forward
driver.navigate().back
driver.navigate().refresh();

Q: What is the order of fastest browser implementation for WebDriver?
A: HTMLUnitDriver is the fastest browser implementation as it does not involves interaction with a browser, This is followed by Firefox driver and then IE driver which is slower than FF driver and runs only on Windows.

Q: Is it possible to use Selenium RC API with Selenium 2.0?
A: You can emulate Selenium 1.0 API with Selenium 2.0 but not all of Selenium 1.0 methods are supported. To achieve this you need to get Selenium instance from WebDriver and use Selenium methods. Method executions might also be slower while simulating Selenium 1.0 with in Selenium 2.0

Q: Can you show me one example of using Selenium 1.0 in Selenium 2.0?
A: Code Sample: // Create web driver instance
     WebDriver driver = new FirefoxDriver();

     // App URL
     String appUrl = "http://www.google.com";

     // Get Selenium instance

Selenium selenium = new WebDriverBackedSelenium(driver, appUrl);

     // Tests using selenium
     selenium.open(appURL);
     selenium.type("name=q", "testData");
     selenium.click("name=btnG");

     // Get back the WebDriver instance

WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver();

Q: I had support of lots of browsers while using Selenium 1.0 and it seems lacking with Selenium 2.0, for example how do I use < awesome> browser while using Selenium 2.0?
A: There is a class called Capabilities which lets you inject new Capabilities in WebDriver. This class can be used to set testing browser as Safari:
//Instantiate Capabilities
     Capabilities capabilities = new DesiredCapabilities()
        
     //Set browser name
     capabilities.setBrowserName("this awesome browser");
         
     //Get your browser execution capabilities

CommandExecutor executor = new SeleneseCommandExecutor("http:localhost:4444/", "http://www.google.com/", capabilities);
        
     //Setup driver instance with desired Capabilities

WebDriver driver = new RemoteWebDriver(executor, capabilities);



Q: Are there any limitations while injecting capabilities in WebDriver to perform tests on a browser which is not supported by WebDriver?
A: Major limitation of injecting Capabilities is that "fundElement" command may not work as expected. This is because WebDriver uses Selenium Core to make "Capability injection" work which is limited by java script security policies.

Q: Can I change User-Agent while using FF browser? I want to execute my tests with a specific User-Agent setting.
A: You can create FF profile and add additional Preferences to it. Then this profile could be passed to Firefox driver while creating instance of Firefox:
FirefoxProfile profile = new FirefoxProfile();

profile.addAdditionalPreference("general.useragent.override", "User Agent String");
     WebDriver driver = new FirefoxDriver(profile);

Q: Is there any difference in XPath implementation in different WebDriver implementations?
A: Since not all browsers (like IE) have support for native XPath, WebDriver provides its own implementation for XPath for such browsers. In case of HTMLUnitDriver and IEDriver, html tags and attributes names are considered lower cased while in case of FF driver they are considered case in-sensitive.

Q: My application uses ajax highly and my tests are suffering from time outs while using Selenium 2.0.
A: You can state WebDriver to implicitly wait for presence of Element if they are not available instantly.  By default this setting is set to 0. Once set, this value stays till the life span of WebDriver object. Following example would wait for 60 seconds before throwing ElementNotFound exception:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
WebElement element = driver.findElement(By.id("elementID"));

Q: What if I don't want to use implicit wait and want to wait only for presence of certain elements?
A: You can use explicit wait in this situation to wait for presence of certain element before continuing with test execution. You can use "WebDriverWait" and "ExpectedCondition" to achieve this:

WebDriver driver = new FirefoxDriver();
WebElement myDynamicElement = (new WebDriverWait(driver, 60)).until(new ExpectedCondition<WebElement>(){
                @Override
     public WebElement apply(WebDriver d) {
          return d.findElement(By.id("myDynamicElement"));
     }});

This is going to wait up to 60 seconds before throwing ElementNotFound exception.

Q: What is RemoteWebDriver? When would I have to use it?
A: RemoteWebDriver is needed when you want to use HTMLUnitDriver. Since HTMLUnitDriver runs in memory, you would not see a browser getting launched:
        // Create HTMLUnitDriver instance
        WebDriver driver = new HtmlUnitDriver();

        // Launch Yahoo.com
        driver.get("http://www.yahoo.com");


Q: What all languages available to be used with WebDriver?
A: Java and C# are on the forefront of WebDriver languages. Support is also available for Python and Ruby. There is also one java script library available for Friefox.

Q: How do I handle java script alert using WebDriver?
A: WebDriver would support handling js alerts using Alert interface.
                 // Bring control on already opened alert
          Alert alert = driver.switchTo().alert();

          // Get the text of the alert or prompt
          alert.getText();
        
// Click ok on alert
          alert.accept();

Q: Could I safely execute multiple instances of WebDriver implementations?
A: As far as HTMLUnitDriver and FF drivers are concerned, each instance would be independent of other. In case of IE driver there could be only one instance of IE driver running on Windows. If you want to execute more than one instance of IE driver then you should consider using RemoteWebDriver and virtual machines.

Q: Is it possible to interact with hidden elements using WebDriver?
A: Since WebDriver tries to exercise browser as closely as real users would, hence simple answer is No, But you can use java script execution capabilities to interact with hidden elements.

Q: I have all my tests written in Selenium 1.0 (Selenium RC), why should I migrate to Selenium 2.0 (WebDriver)?
A: Because:
WebDriver has more compact and object oriented API than Selenium 1.0
WebDriver simulates user behaviour more closely than Selenium 1.0, for example if a text box is disabled WebDriver would not be able to type text in it while Selenium 1.0 would be
WebDriver is supported by Browser vendor themselves i.e. FF, Opera, Chrome etc

Q: My XPath and CSS locators don't always work with Selenium 2.0, but they used to with Selenium 1.0.
A: In case of XPath, it is because WebDriver uses native browser methods unless it is not available. And this cause complex XPath to be broken. In case of Selenium 1.0 css selectors are implemented using Sizzle Library and not all the capabilities like "contains" are available to be used with Selenium 2.0

Q: How do I execute Java Script in Selenium 2.0?
A: You need to use JavaScriptExecutor to execute java script in Selenium 2.0, For example if you want to find tag name of an element using Selenium 2.0 then you can execute java script as following:
WebElement element = driver.findElement(By.id("elementLocator"));

String name = (String) ((JavascriptExecutor) driver).executeScript(
     "return arguments[0].tagName", element);

Q: Why does not my java script execution return any value?
A: This might happen when you forget to add "return" keyword while executing java script. Notice the "return" keyword in following statement:
((JavascriptExecutor) driver).executeScript("return window.title;");

Q: Are there any limitations from operating systems while using WebDriver?
A: While HTMLUnitDriver, FF Driver and Chrome Driver could be used on all operating systems, IE Driver could be used only with Windows.

Q: Give me architectural overview of WebDriver.
A: WebDriver tries to simulate real user interaction as much as possible. This is the reason why WebDriver does not have "fireEvent" method and "getText" returns the text as a real user would see it. WebDriver implementation for a browser is driven by the language which is best to driver it. In case of FF best fit languages are Javascript in an XPCOM component and in IE it is C++ using IE automation.  Now the implementation which is available to user is a thin wrapper around the implementation and user need not know about implementation.

Q: What is Remote WebDriver Server?
A: Remote WebDriver Server has two components -client and server. Client is WebDriver while Server is java servlet. Once you have downloaded selenium-server-standalone-<version-number>.jar file you can start it from command line as:</version-number>
java -jar selenium-server-standalone-<version-number>.jar
          

Q: Is there a way to start Remote WebDriver Server from my code?
A: First add Remote WebDriver jar in your class path. You also need another server called "Jetty" to use it. You can start sever as following:
                        WebAppContext context = new WebAppContext();
         context.setContextPath("");
         context.setWar(new File("."));
         server.addHandler(context);

         context.addServlet(DriverServlet.class, "/wd/*");

SelectChannelConnector connector = new SelectChannelConnector();
         connector.setPort(3001);
         server.addConnector(connector);

         server.start();

Q: But what are the advantages of using Remote WebDriver over WebDriver?
A: You can use Remote WebDriver when:

When you want to execute tests on a browser not available to you locally
Introduction to extra latency to tests
But there is one disadvantage of using Remote WebDriver that you would need external servlet container.

Q: Can you show me code example of using Remote WebDriver?
A: // Any driver could be used for test
DesiredCapabilities capabilities = new DesiredCapabilities();

          // Enable javascript support
          capabilities.setJavascriptEnabled(true);

          // Get driver handle
          WebDriver driver = new RemoteWebDriver(capabilities);

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

Q: What are the modes of Remote WebDriver
A: Remote WebDriver has two modes of operations:
Client Mode: This is where language bindings connect to remote instance. FF drive and RemoteWebDriver clients work this way.
Server Mode: In this mode language bindings set up the server. ChromeDriver works this way.


Q: What Design Patterns could be used while using Selenium 2.0?
A: These three Design Patterns are very popular while writing Selenium 2.0 tests:


1. Page Objects -which abstracts UI of web page
2. Domain Specific Language -which tries to write tests which could be understood by a normal user having no technical knowledge
3. Bot Style Tests -it follows "command-like" test scripting

Q: So do I need to follow these Design patterns while writing my tests?
A: Not at all, these Design Patterns are considered best practices and you can write you tests without following any of those Design Patterns, or you may follow a Design Pattern which suites your needs most.

Q: Is there a way to enable java script while using HTMLUnitDriver?
A: Use this:
HtmlUnitDriver driver = new HtmlUnitDriver();
     driver.setJavascriptEnabled(true);

or this:
     HtmlUnitDriver driver = new HtmlUnitDriver(true);

Q: Is it possible to emulate a browser with HTMLUnitDriver? 
A: You can emulate browser while using HTMLUnitDriver but it is not recommended as applications are coded irrespective of browser you use. You could emulate Firefox 3 browser with HTMLUnitDriver as:
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3);
Or you can inject desired capabilities while instantiating HTMLUnitDriver as:
HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);
    
Q: How do I use iPhone Driver?
A: You should start iPhone SDK and build iPhone driver. Down load iPhone development tools and provision profile. Now iPhone driver can connect through HTTP to the iphone simulator. You can also run simulator on another machine in your network and WebDriver could connect to it remotely.

Q: Is it possible to convert Selenium IDE test to WebDriver test?
A: For now there is no formatter available to convert Selenium IDE tests to corresponding WebDriver tests, hence simple answer is No. Yes WebDriver style of code can be generated from Selenium IDE

Q: Can WebDriver handle UntrustedSSLCertificates?
A: This feature is currently supported in Firefox browser and is awaiting implementation in IE and Chrome drivers.

Q: Can I carry out multiple operations at once while using WebDriver?
A: You can use Builder pattern to achieve this. For example if you want to move an element from one place to another you can use this:
          Actions builder = new Actions(driver);
          Action dragAndDrop = builder.clickAndHold(element)
                 .moveToElement(otherElement)
                 .release(otherElement)
                 .build();

          dragAndDrop.perform();

Q: How do I simulate keyboard keys using WebDriver?
A: There is a KeyBoard interface which has three methods to support keyboard interaction:
sendKeys(CharSequence)- Sends character sequence
pressKey(Keys keyToPress) - Sends a key press without releasing it.
releaseKey(Keys keyToRelease) - Releases a modifier key

Q: What about Mouse Interaction?
A: Mouse interface lets you carry out following operations:
click(WebElement element) -Clicks an element
doubleClick(WebElement element) - Double-clicks an element.
void mouseDown(WebElement element) - Holds down the left mouse button on an element.
mouseUp(WebElement element) - Releases the mouse button on an element.
mouseMove(WebElement element) - Moves element form current location to another element.
contextClick(WebElement element) - Performs a context-click (right click) on an element.

Q: How does Android Webdriver works?
A: Android WebDriver uses Remote WebDriver. Client Side is test code and Server side is application installed on android emulator or actual device. Here client and server communicate using JSON wire protocol consisting of Rest requests.

Q: What are the advantages of using Android WebDriver?
A: Android web driver runs on Android browser which is best real user interaction. It also uses native touch events to emulated user interaction.
But there are some drawbacks also like, it is slower than headless WebKit driver. XPath is not natively supported in Android web view.

Q: Is there a built-in DSL (domain specific language) support available in WebDriver?
A: There is not, but you can easily build your own DSL, for example instead of using:
webDriver.findElement(By.name("q")).sendKeys("Test");

You can create a more composite method and use it:
public static void findElementAndType(WebDriver webDriver, String elementLocator, String testData) {
                webDriver.findElement(By.name(elementLocator)).sendKeys(testData);
}
And now you just need to call method findElementAndType to do type operation.

Q: What is grid2?
A: Grid2 is Selenium grid for Selenium 1 as well as WebDriver, This allows to:

Execute tests on parallel on different machines
Managing multiple environments from one point

Q: How do I start hub and slaves machines in grid 2?
A: Navigate to you selenium server standalone jar download and execute following command:
                java -jar selenium-server-standalone-<version number="">.jar</version> -role hub
And you start Slave machine by executing following command:
                Java:jar selenium-server-<version number="">.jar:role webdriver  -hub http://localhost:4444/grid/register -port 6666</version>


Q: And how do I run tests on grid?
A: You need to use the RemoteWebDriver and the DesiredCapabilities object to define browser, version and platform for testing. Create Targeted browser capabilities as:
DesiredCapabilities capability = DesiredCapabilities.firefox();
Now pass capabilities to Remote WebDriver object:
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
Following this, hub will take care of assigning tests to a slave machine

Q: What parameters can be passed to grid2?
A: You can pass following parameters to grid 2:
-port 4444 (default 4444)
-nodeTimeout (default 30) the timeout in seconds before the hub automatically releases a node that hasn't received any requests for more than the specified number of seconds.
-maxConcurrent 5 (5 is default) The maximum number of browsers that can run in parallel on the node.

Selenium Tool Implementation Misc Questions

Q: How do I implement data driven testing using Selenium?
A: Selenium, unlike others commercial tools does not have any direct support for data driven testing. Your programming language would help you achieving this. You can you jxl library in case of java to read and write data from excel file. You can also use Data Driven Capabilities of TestNG to do data driven testing.

Q: What is equivalent to test step, test scenario and test suite in Selenium.
A: If you are using Java client driver of Selenium then TestNG test method could be considered equivalent to test step, a test tag could be considered as test scenario and a suite tag could be considered equivalent to a test suite.

Q: How do I get attribute value of an element in Selenium?
A: You could use getAttribute method
With Selenium 1.0:
        String var = selenium.getAttribute("css=input[name='q']@maxlength");
        System.out.println(var);

With Selenium 2.0:
String var = webDriver.findElement(By.cssSelector("input[name='q']")).getAttribute("maxlength")
        System.out.println(var);

Q: How do I do database testing using Selenium?
A: Selenium does not support database testing but your language binding does. For example while using java client driver you can use java data base connectivity (jdbc) to establish connection to data base, fetch/write data to data base and doing data comparison with front end.

Q: I completed test execution and now I want to email test report.
A: If you are using "ant" build tool then you can use "mail" task to deliver your test results. Similar capabilities are available in Continuous Build Integration tools like -Hudson.

Q: How do I make my tests more comprehensible?
A: Selenium tests which are written as:
        selenium.click("addForm:_ID74:_ID75:0:_ID79:0:box");

Make it tough to understand the element which is being exercised upon.
Instead of hard coding element locator in tests you should externalize them. For example with java you can use properties file to contain element locators and then locator reference is given in test script. Following this approach previous test step would look as:
      selenium.click(PolicyCheckbox);

And this is far more comprehensible.

Q: Why should I use Page Object?
A: Page object is a design pattern which distinguishes the code carrying out operations on page and code which carries out tests (assertion/verification). While implementing page object you abstract functioning of a page or part of it in a dedicated "Classs" which is then used by test script to perform actions on page and reach a stage when actual test could be performed.
Advantage of using page object is the fact that if application lay out changes then you only need to modify the navigation part and test would function intact.


7 comments:

  1. Looking for best Software Testing Training in Chennai? CREDO SYSTEMZ is the No 1 Software Testing Training Institute in Chennai offering professional training on both Manual, automation testing training like Selenium, QTP/UFT and Performance Testing Training Courses like LoadRunner and JMeter. More Details: Software Testing Training course details.

    ReplyDelete
  2. I really enjoy the blog.Much thanks again. Really Great. selenium Online Training Bangalore

    ReplyDelete
  3. In the question "How can you find if an element in displayed on the screen?"

    boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isDisplayed(); is there but it should be
    isSelected():
    boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isSelected();

    ReplyDelete
  4. Good Post. I like your blog. Thanks for Sharing.....
    Selenium course in Noida

    ReplyDelete
  5. The article is more informative. This is more helpful for our selenium training in chennai. Thanks for sharing

    ReplyDelete