Search This Blog

Tuesday 19 April 2016

Selenium Interview Questions

  1. How to configure the framework in to eclipse?
  2. Following are the steps to configure framework in eclipse:
  • Extract the provided zip folder
  • Open eclipse and create a new project using the extracted zip folder
  • Run the sample test script RegistrationTest.java by using the JUnit option
  • Create new test scripts in the folder ‘TestScipts’ and run them using JUnit option
  1. Does the framework work only for java language?
  2. The framework is made in Java language but is language agnostic and can be used with any language.
  3. What is meant by Page Object Model design?
  4. Page Object Model is a simple design pattern that models each page (or page chunk) as a class object that other classes / objects can interact with.
  5. Where can I see the generated reports?
  6. We can see the HTML view of generated reports:
  • Run the build.xml as Ant Build
  • Refresh the project and open the Reports folder
  • From the Reports folder, open the index.html file with Web Browser
  1. How can I change the browser to be used for running the test scripts?
  2. Following are the steps:
  • Go to the config folder
  • Open the “gui_automation.properties” file
  • Uncomment the needed browser configuration and comment the not needed browser in this file and save the file
  1. Does WebDriver support file uploads?
  2. Yes, it is possible if you call WebElement#sendKeys(“/path/to/file”) on a file upload element. Make sure you don’t use WebElement#click() on the file upload element or the browser will hang.
  3. What input fields have been targeted in v3 of the framework using parameterization
  4. Text boxes, radio buttons, drop downs, check boxes, auto-suggest search drop down, and file upload.
  5. How can I handle multiple windows?
  6. You can handle multiple windows using the “WebDriver.switchTo().window()” method – here window name is required. If the name is not known, you can use “WebDriver.getWindowHandles()” to obtain a list of known windows and then switch to a specific window.
  7. Can I make webdriver to wait for some event on default?
  8. Yes.
    Example: new WebDriverWait(driver,20).until(ExpectedConditions.presenceOfElementLocated(B y.id(“loginBox”)))
  9. Does the framework support the .xlsx extension files for parameterization?
  10. Yes. We have provided support for .xlsx extension files i.e. 2007-2010 format, using Apache POI.
  11. When I can use implicit and explicit wait?
  12. Implicit wait will be used when you need to wait for all elements in script, while Explicit wait method will be used only for particular specified elements. Explicit wait will be preferred for dynamically loading ajax elements.
    Implicit wait Example:
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    Explicit Wait Example:
    public static WebElement explicitWait(WebDriver driver,By by){
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.presenceOfElementLocated(by)); }
  13. Which command should be used to quit WebDriver instance?
  14. The quit() method is used to quit WebDriver instance. That is:
    driver.quit();
  15. How can I drag element from one position and drop to second position?
  16. This event can be implemented by using Action interface. Example:
    Actions builder = new Actions(driver);
    Action dragAndDrop = builder.clickAndHold(someElement).
    moveToElement(otherElement).release(otherElement).build();
    dragAndDrop.perform();
  17. How can I move backwards or forwards in browser’s history in Webdriver?
  18. You can move backwards and forwards in browser’s history as below:
    //To go backward
    driver.navigate().back();
    //To go forward
    driver.navigate().forward();
  19. How can I get title of the window?
  20. You can get the title of the window by using getTitle() method:
    String title = driver.getTitle();
    System.out.println(“Title of the page is “+title);
  21. How to Maximize the browser to screen size?
  22. To maximize the browser window to screen size Toolkit.getScreenSize() method is used:
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenResolution = new Dimension((int)
    toolkit.getScreenSize().getWidth(), (int)
    toolkit.getScreenSize().getHeight());
    driver.manage().window().setSize(screenResolution);
  23. How to handle pageload time in webdriver?
  24. You can set the PageLoadTimeout value to whatever you need using:
    driver.Timeouts.PageLoadTimeout(XX, SECONDS)
    where XX is the number of seconds you want the timeout to be set to.
  25. How can i get text from alert window ?
  26. To get text from alert box, first you have to switch on alert, and then you can use getText method:
    Alert alert = driver.switchTo().alert();
    // Get the text from the alert
    String alertText = alert.getText();
—————————————————————————————————————————————————-
Selenium Automation (IDE, Grid, RC, WebDriver) FAQ’s
Selenium Automation Interview Questions
Question 1:
What is Selenium?
Answer:
Selenium is a browser automation tool which lets you automated operations like – type, click, and selection from a drop down of a web page.
Question 2:
How is Selenium different from commercial browser automation tools?
Answer:
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.
Question3:
What are the set of tools available with Selenium?
Answer:
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.
Question 4:
Which Selenium Tool should I use?
Answer:
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
Question 5:
What is Selenium IDE?
Answer:
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.
Question 6:
Which language is used in Selenium IDE?
Answer:
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
Question 7:
What is Selenium 1.0?
Answer:
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.
Question 8:
What is Selenium 2.0?
Answer:
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 does
  • supports more UI complicated UI operations like drag and drop
Question 9:
What are the element locators available with Selenium which could be used to locate elements on web page?
Answer:
There are mainly 4 locators used with Selenium –
  • html id
  • html name
  • XPath locator and
  • Css locators
Question 10:
What is Selenium Grid?
Answer:
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
Question 11:
What are two modes of views in Selenium IDE?
Answer:
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.
Question 12:
Can I control the speed and pause test execution in Selenium IDE?
Answer:
Selenium IDE provides a slider with Slow and Fast pointers to control the speed of execution.
Question 13:
Where do I see the results of Test Execution in Selenium IDE?
Answer:
Result of test execution can be views in log window in Selenium IDE –
Question 14:
Where do I see the description of commands used in Selenium IDE?
Answer:
Commands of description can be seen in Reference section –
Question 15:
Can I build test suite using Selenium IDE?
Answer:
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.
Question 16:
What verification points are available with Selenium?
Answer:
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)
Question 17:
I see two types of check with Selenium – verification and assertion, what’s the difference between tow?
Answer:
  • 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.
Question 18:
I don’t see check points added to my tests while using Selenium IDEL, how do I get them added to my tests?
Answer:
You need to use context menu to add check points to your Selenium IDE tests –
Question 19:
How do I edit tests in Selenium IDE?
Answer:
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 –
Question 20:
What is syntax of command used in Selenium?
Answer:
There are three entities associated with a command –
  • Name of Command
  • Element Locator (also known as Target)
  • Value (required when using echo, wait etc)
Question 21:
There are tons of Selenium Command, am I going to use all of them
Answer:
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.
Question 22:
How do I use html id and name while using Selenium IDE
Answer:
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 –
Question 23:
What is XPath? When would I have to use XPath in Selenium IDE?
Answer:
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’)]
Question 24:
What is CSS location strategy in Selenium?
Answer:
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’)
Question 25:
There is id, name, XPath, CSS locator, which one should I use?
Answer:
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.
Question 26:
I want to generate random numbers, dates as my test data, how do I do this in Selenium IDE?
Answer:
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()}
Question 27:
Can I store result of an evaluation and use it later in my test?
Answer:
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}
Question 28:
I have stored result of an evaluation; can I print it in IDE to check its value?
Answer:
You can use echo command as following to check the stored value in Selenium IDE –
storeText
css=input#s
var1
echo
${var1}
Question 29:
Can I handle java script alert using Selenium?
Answer
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.
Question 30:
Selenium has recorded my test using XPath, how do I change them to css locator?
Answer
You can use drop down available next to Find in Selenium to change element locator used by Selenium –
Question 31:
I have written my own element locator, how do I test it?
Answer
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.
Question 32:
I have written one js extension; can I plug it in Selenium and use it?
Answer
You could specify you js extension in “Options” window of Selenium IDE –
Question 33:
How do I convert my Selenium IDE tests from Selenese to another language?
Answer
You could use Format option of Selenium IDE to convert tests in another programming language –
Question 34:
I have converted my Selenium IDE tests to java but I am not able to execute themL, execution options as well as Table tab of Selenium IDE is disabledLL
Answer
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.
Question 35:
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?
Answer
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.
Question 36:
I have added one command in middle of list of commands, how do I test only this new command?
Answer
You can double click on newly added command and Selenium IDE would execute only that command in browser.
Question 37:
Can I make Selenium IDE tests begin test execution from a certain command and not from the very first command?
Answer
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
Question 38:
Are there other tools available outside Selenium IDE to help me tests my element locators
Answer
You could XPath checker – https://addons.mozilla.org/en-US/firefox/addon/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.
Question 39:
What is upcoming advancement in Selenium IDE?
Answer
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
Question 40:
How can I use looping option (flow control) is Selenium IDE
Answer
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 – http://51elliot.blogspot.com/2008/02/selenium-ide-goto.html
This extension can be added under “Selenium IDE Extension” section to use loop feature in Selenium IDE.

Question 41:
Can I use screen coordinate while using click command? I want to click at specific part of my element.
Answer
You would need to use clickAT command to achieve. clickAt command accepts element locator and x, y coordinates as arguments –
clickAt(locator, coordString)
Question 42:
How do I verify presence of drop down options using Selenium?
Answer
Use assertSelectOptions as following to check options in a drop down list –
assertSelectOptions
Question 43:
Can I get data from a specific html table cell using Selenium IDE?
Answer
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
Question 44:
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?
Answer
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.
Question 45:
My application has dynamic alerts which don’t always appear, how do I handle them?
Answer
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 ( )
Question 46:
Can I right click on a locator?
Answer
You can use command – contextMenu ( locator) to simulate right click on an element in web page.
Question 47:
How do I capture screen shot of page using Selenium IDE?
Answer
Use command – captureEntirePageScreenshot to take screen shot of page.
Question 48:
I want to pause my test execution after certain command.
Answer
Use pause command which takes time in milliseconds and would pause test execution for specified time – pause ( waitTime )
Question 49:
I used open command to launch my page, but I encountered time out errorL
Answer
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.
Question 50:
What’s the difference between type and typeKeys commands?
Answer
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
Question 51:
What is Selenium RC (also known as Selenium 1.0)?
Answer
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
Question 52:
What are the main components of Selenium RC?
Answer
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)
Question 53:
Why do I need Selenium Server?
Answer
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.
Question 54:
What is Selenium core? I have never used it!!!
Answer
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.
Question 55:
Where is executable for Selenium RC, how do I install it?
Answer
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.
Question 56:
I have downloaded Selenium Server and Client libraries, how do I start Selenium Server?
Answer
To start Selenium Server, you need to navigate to installation directory of Selenium server and execute following command –
Java -jar .jar
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.
Question 57:
On my machine port 4444 is not freeL . How do Use another port?
Answer
You can specify port while running the selenium server as –
Java -jar .jar –port 5555
Question 58:
I am new to programming; can Selenium generate sample code from my Selenese scripts?
Answer
You can first record tests in Selenium IDE and then use format option to convert them in a language of your choice.
Question 59:
Can I start Selenium server from my program instead of command line
Answer
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();
Question 60:
And how do I start the browser?
Answer
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
Question 61:
I am not using java to program my tests, do I still have to install java on my system?
Answer
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.
Question 62:
What are the browsers offering from Selenium?
Answer
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
Question 63:
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?
Answer
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 .jar –singleWindow
Question 64:
My tests usually time outL. Can I specify bigger time out?
Answer
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 .jar –timeout
Question 65:
My system is behind corporate network, how do I specify my corporate proxy?
Answer
You can specify your corporate proxy as following while starting Selenium Server –
java -jar .jar -Dhttp.proxyHost= -Dhttp.proxyPort= -Dhttp.proxyUser= -Dhttp.proxyPassword=
Question 66:
I am switching domains in my test scripts. I move from “yahoo.com” to “google.com” and my tests encounter permission denied errorL
Answer
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 .jar –proxyInjectionMode
Now Selenium server would act as proxy server for all the content going to test application
Question 67:
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
Answer
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
Question 68:
Can I log more options during test execution?
Answer
If you want to log browser side option during test execution then you should start Selenium server as following –
java -jar <>.jar –browserSideLog
Question 69:
Can I use Selenium RC on my UNIX/Mac also?
Answer
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
Question 70:
I want to test my scripts on new experimental browser, how do I do that?
Answer
You can specify *custom followed by path to browser to execute your tests on any browser while starting Selenium server
*custom
Question 71:
I executed my tests cases but where is the test report?
Answer
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.
Question 72:
How do I use recovery scenarios with Selenium? I used to use them with QTP.
Answer
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.
Question 73:
How do I iterate through options in my test script.
Answer
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);
}
Question 74:
Can I execute java script from my tests? I want to count number of images on my page.
Answer
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’);”);
Question 75:
Is there a way for me to know all available options when I start Selenium Server?
Answer
If you want to see all options available while starting Selenium server then you should use option “-h” while starting Selenium server –
Java –jar .jar –h
It would display you all the options which you can use while starting the Selenium server.
Question 76:
I have created my own firefox profile; can I execute my test scripts on it
Answer
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 .jar -firefoxProfileTemplate   “awesome location”
Question 77:
How do I capture server side log from Selenium server?
Answer
Start your Selenium Server as following –
java -jar .jar -log selenium.log
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
Question 78:
What are Heightened Privileges Browsers?
Answer
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
Question 79:
My application has lots of pop up window, how do I work with them?
Answer
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 J
Question 80:
While trying to execute my tests with firefox I encountered following error – “Firefox Refused Shutdown While Preparing a Profile”. How do I solve it?
Answer
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
Question 80:
While trying to execute my tests with firefox I encountered following error – “Firefox Refused Shutdown While Preparing a Profile”. How do I solve it?
Answer
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

Question 81:
My application uses Ajax heavily how do I use Selenium RC to work with Ajax operations?
Answer
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);
}
Question 82:
How do I upload a file using Selenium? I need to upload a word file during test execution.
Answer
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.
Question 83:
Why do I get “permission denied” error during execution of Selenium tests?
Answer
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.
Question 84:
I am not able to use “style” attribute to locate element with IE browserL
Answer
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
Question 85:
Are there any technical limitations while using Selenium RC?
Answer
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.
Question 86:
But my tests need me to exercise objects outside browser, how do I achieve it?
Answer
You can use Robot class in java to achieve this, but it would be dirty solution even if you get through this.
Question 87:
Does Selenium have any offering for mobile browsers?
Answer
Selenium 2.0 (WebDriver) provides iPhone as well Android drivers which could be used to drive tests on mobile browsers
Question 88:
How does Selenium RC stand with other commercial tools?
Answer
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.
Question 89:
How does Selenium RC stand with other commercial tools?
Answer
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
Question 90:
Can I just use Selenium RC to drive tests on two different browsers on one operating system without using Selenium Grid?
Answer
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 SYSTEM “http://testng.org/testng-1.0.dtd” &gt;
<suite name=“Test Automation” verbose=“10”>
<parameter name=“serverHost” value=“localhost” />
<parameter name=“appURL” value=http://tamil.yahoo.com&#8221;/>
<parameter name=“proxyInjection” value=“false” />
<parameter name=“serverPort” value=“4444”/>
<test name=“Web Test1”>
<parameter name=“browser” value=“*chrome” />
<parameter name=“m” value=“1”>parameter>
<classes><class name=com.core.tests.TestClass1>class>classes>
test>
<test name=“Web Test2”>
<parameter name=“browser” value=“*iehta” />
<parameter name=“m” value=“2”>parameter>
<classes><class name=com.core.tests.TestClass1>class>classes>
test>
suite>
Selenium Grid Questions
Question 91:
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.
Answer
Selenium grid is your friendJ. Selenium grid lets you distribute tests across browsers and machines of your choice.
Question 92:
How does Selenium grid works?
Answer
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.
Question 93:
Can you show me one diagram which describes functionality of Selenium grid?
Answer
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
Question 94:
Which jar files are needed to works with Selenium GRID?
Answer
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-.jar
  • selenium-grid-hub-standalone-.jar
  • selenium-grid-tools-standalone-.jar
Question 95:
How do I start Selenium Grid hub from my machine?
Answer
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
Question 96:
How do I start Selenium Grid Slave Server from my system?
Answer
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”
Question 97:
How do I start Selenium grid slave on a different port than 5555?
Answer
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
Question 98:
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?
Answer
You should specify following configuration while starting RC slave –
ant -Dport= -Dhost= -DhubURL= launch-remote-control
Herein “hostname” is the host where RC slave is running and “hub url” is URL of machine where grid hub is running.
Question 99:
How do I specify an environment while starting grid slave machine?
Answer
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.
Question 100:
How do I use machine specific configuration in my Selenium tests?
Answer
You could specify machine specific configuration while instantiating Selenium as –
Selenium = new DefaultSelenium(“localhost”, 4444, **’Safari on Mac’**, ‘http://yahoo.com&#8217;);
And then you use this selenium instance to carryout operation on your web application.
Question 101:
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?
Answer
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 –
Question 102:
How does Selenium grid hub keeps in touch with RC slave machine?
Answer
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.
Question 103:
My RC becomes unresponsive at times and my Selenium grid hub keeps waiting for RC slave to respondL. How do I let hub know to give up on RC slave after a certain time?
Answer
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.
Question 104:
What if my hub goes down while Selenium RC slaves are up and running?
Answer
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= launch-hub
if hub does not respond within this time then RC slaves deregister themselves from hub.
Question 105:
Can Selenium grid be used for performance testing?
Answer
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.
Question 106:
Are there additional logs available while working with Selenium grid?
Answer
You can find Selenium grid hub logs in “log/hub.log” and Remote Control logs in “log/rc-*.log” folder.
Question 107:
There are various options available while starting a Selenium server, how do I use them with Selenium grid?
Answer
You can use “seleniumArgs” 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
Question 108:
I see duplicate entries in my hub console, same RC slave listed more than once :-O
Answer
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.
Question 109:
How do I specify my corporate proxy while starting Selenium grid hub or slave machines?
Answer
You could use setting for “http.proxyHost” abd “http.proxyPort” while starting hub and remote control machines –
ant -Dhttp.proxyHost= -Dhttp.proxyPort= launch-hub
ant -Dhttp.proxyHost= -Dhttp.proxyPort= launch-remote-control
Question 110:
How do I use Selenium Grid while using Java, .Net or Ruby
Answer
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
Question 111:
How about the test report when I use Selenium grid for test execution?
Answer
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
Question 112:
What is Selenium 2.0? I have heard this buzz word many times.
Answer
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.
Question 113:
Why are two tools being combined as Selenium 2.0, what’s the gain?
Answer
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.
Question 114:
So everyone is going to use Selenium 2.0?
Answer
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
Question 115:
So how do I specify my browser configurations with Selenium 2.0?
Answer
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.
Question 116:
How is Selenium 2.0 configuration different than Selenium 1.0?
Answer
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.
Question 117:
Can you show me one code example of setting Selenium 2.0?
Answer
Here is java example of initializing firefox driver and using Google Search engine –
protected WebDriver webDriver;
//@BeforeClass(alwaysRun=true)
public void startDriver(){
webDriver = new FirefoxDriver();
// Get Google search page and perform search on term “Test”
webDriver.get(“http://www.google.com&#8221;);
webDriver.findElement(By.name(“q”)).sendKeys(“Test”);
webDriver.findElement(By.name(“btnG”)).click();
Question 118:
Which web driver implementation is fastest?
Answer
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
Question 119:
What all different element locators are available with Selenium 2.0?
Answer
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));
Question 120:
How do I submit a form using Selenium?
Answer
You can use “submit” method on element to submit form –
element.submit();
Alternatively you can use click method on the element which does form submission.
Question 121:
Can I simulate pressing key board keys using Selenium 2.0?
Answer
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”);
Question 122:
How do I clear content of a text box in Selenium 2.0
Answer
You can use “clear” method on text box element to clear its content –
textBoxElement.clear();
Question 123:
How do I select a drop down value using Selenium2.0?
Answer
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”);
Question 124:
What are offering to deal with popup windows while using Selenium 2.0?
Answer
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);
}
Question 125:
How about handling frames using Selenium 2.0?
Answer
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 4th sub frame names “parentFrame”
Question 126:
Can I navigate back and forth in a browser in Selenium 2.0?
Answer
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();
Question 127:
What is the order of fastest browser implementation for WebDriver?
Answer
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.
Question 128:
Is it possible to use Selenium RC API with Selenium 2.0?
Answer
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
Question 129:
Can you show me one example of using Selenium 1.0 in Selenium 2.0?
Answer
Code Sample:
// Create web driver instance
WebDriver driver = new FirefoxDriver();
// App URL
String appUrl = “http://www.google.com&#8221;;
// 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();

Question 130:
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?
Answer
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/&#8221;, capabilities);
//Setup driver instance with desired Capabilities
WebDriver driver = new RemoteWebDriver(executor, capabilities);

Question 131:
Are there any limitations while injecting capabilities in WebDriver to perform tests on a browser which is not supported by WebDriver?
Answer
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.
Question 132:
Can I change User-Agent while using FF browser? I want to execute my tests with a specific User-Agent setting.
Answer
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);
Question 133:
Is there any difference in XPath implementation in different WebDriver implementations?
Answer
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.
Question 134:
My application uses ajax highly and my tests are suffering from time outs while using Selenium 2.0L.
Answer
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”));
Question 135:
What if I don’t want to use implicit wait and want to wait only for presence of certain elements?
Answer
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.
Question 136:
What is RemoteWebDriver? When would I have to use it?
Answer
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&#8221;);
Question 137:
What all languages available to be used with WebDriver?
Answer
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.
Question 138:
How do I handle java script alert using WebDriver?
Answer
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();
Question 139:
Could I safely execute multiple instances of WebDriver implementations?
Answer
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.
Question 140:
Is it possible to interact with hidden elements using WebDriver?
Answer
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.
Question 141:
I have all my tests written in Selenium 1.0 (Selenium RC), why should I migrate to Selenium 2.0 (WebDriver)?
Answer
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
Question 142:
My XPath and CSS locators don’t always work with Selenium 2.0, but they used to with Selenium 1.0L.
Answer
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
Question 143:
How do I execute Java Script in Selenium 2.0?
Answer
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) ((JavascriptExecutordriver).executeScript(
“return arguments[0].tagName”, element);
Question 144:
Why does not my java script execution return any value?
Answer
This might happen when you forget to add “return“ keyword while executing java script. Notice the “return” keyword in following statement –
((JavascriptExecutordriver).executeScript(“return window.title;”);
Question 145:
Are there any limitations from operating systems while using WebDriver?
Answer
While HTMLUnitDriver, FF Driver and Chrome Driver could be used on all operating systems, IE Driver could be used only with Windows.
Question 146:
Give me architectural overview of WebDriver.
Answer
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.
Question 147:
What is Remote WebDriver Server?
Answer
Remote WebDriver Server has two components – client and server. Client is WebDriver while Server is java servlet. Once you have downloaded selenium-server-standalone-.jar file you can start it from command line as –
java -jar selenium-server-standalone-<version-number>.jar
Question 148:
Is there a way to start Remote WebDriver Server from my code?
Answer
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();
Question 149:
But what are the advantages of using Remote WebDriver over WebDriver?
Answer
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.
Question 150:
Can you show me code example of using Remote WebDriver?
Answer
// 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&#8221;);
Question 151:
What are the modes of Remote WebDriver
Answer
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.
Question 152:
What Design Patterns could be used while using Selenium 2.0?
Answer
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
Question 153:
So do I need to follow these Design patterns while writing my tests?
Answer
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.
Question 154:
Is there a way to enable java script while using HTMLUnitDriver?
Answer
Use this –
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);
or this –
HtmlUnitDriver driver = new HtmlUnitDriver(true);
Question 155:
Is it possible to emulate a browser with HTMLUnitDriver?
Answer
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);
Question 156:
How do I use iPhone Driver?
Answer
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.
Question 157:
Is it possible to convert Selenium IDE test to WebDriver test?
Answer
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
Question 158:
Can WebDriver handle UntrustedSSLCertificates?
Answer
This feature is currently supported in Firefox browser and is awaiting implementation in IE and Chrome drivers.
Question 159:
Can I carry out multiple operations at once while using WebDriver?
Answer
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();
Question 160:
How do I simulate keyboard keys using WebDriver?
Answer
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
Question 161:
What about Mouse Interaction?
Answer
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.
Question 162:
How does Android Webdriver works?
Answer
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.
Question 163:
What are the advantages of using Android WebDriver?
Answer
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.
Question 164:
Is there a built-in DSL (domain specific language) support available in WebDriver?
Answer
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.
Question 165:
What is grid2?
Answer
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
Question 166:
How do I start hub and slaves machines in grid 2?
Answer
Navigate to you selenium server standalone jar download and execute following command –
java -jar selenium-server-standalone-.jar -role hub
And you start Slave machine by executing following command –
Java –jar selenium-server-.jar –role webdriver  -hubhttp://localhost:4444/grid/register -port 6666
Question 167:
And how do I run tests on grid?
Answer
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&#8221;), capability);
Following this, hub will take care of assigning tests to a slave machine
Question 168:
What parameters can be passed to grid2?
Answer
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
Question 169:
How do I implement data driven testing using Selenium?
Answer
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.
Question 170:
What is equivalent to test step, test scenario and test suite in Selenium.
Answer
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.
Question 171:
How do I get attribute value of an element in Selenium?
Answer
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);
Question 172:
How do I do database testing using Selenium?
Answer
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.
Question 173:
I completed test execution and now I want to email test report.
Answer
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.
Question 174:
How do I make my tests more comprehensible?
Answer
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.
Question 175:
Why should I use Page Object?
Answer
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
—————————————————————————————————————————————————-
1) What is test automation or automation testing?
Automation testing is used to automate the manual testing. It is a process of automating the manual process to test the application/system under test. It uses separate testing tools which facilitate you to create test scripts which can be executed repeatedly and doesn’t need any manual intervention.
2) What are the advantages of automation testing?
  • It supports execution of repeated test cases.
  • It facilitates parallel execution.
  • It aids in testing a large test matrix.
  • It improves accuracy because there are no chances of human errors.
  • It saves time and money.
3) What is selenium? What are the different components of selenium?
Selenium is one of the most popular automated testing suites. It is browser automation tool which lets you automated operations like click, type and selection from a drop down of a web page. It is designed to support and encourage automation testing of functionalities of web based applications and a wide range of browsers and platforms. It is one of the most accepted tools amongst the testing professional due to its existence in the open source community.
Selenium is not just a single tool rather than it is a package of several testing tools and that?s why it is referred as a suite. Each of these tools is designed to cater different testing and test environment requirement.
4) What is Selenium 1.0?
Selenium 1.0 is popularily known as Selenium Remote Control (Selenium RC). It is a library available in wide variety of languages. The main reason to use Selenium RC was that Selenium IDE was incapable to execute tests in browsers other than Selenium IDE and the limitation of language Selenese used in Selenium IDE.
5) What is Selenium IDE?
Selenium IDE is a firefox plug-in. It is used to record and replay tests in firefox browser. It is used only with firefox browser.
6) What is selenium 2.0?
Selenium 2.0 is a tool which is a combination of web testing tools Selenium RC and WebDriver.
7) Why is selenium selected as a test tool?
Selenium is used as a testing tool because:
  • It is free and open source.
  • It has a large user base and helping communities.
  • Compatible on different platforms i.e. Windows, Mac OS, Linux etc.
  • Have cross browser compatibility (Chrome, Firefox, IE, Safari etc.)
  • Support multiple programming languages ( Java, C#, Ruby, PERL, Python etc.)
  • Support distributed testing.
8) What are selenium supporting testing types?
Selenium supports two types of testing:
  • Functional Testing
  • Regression Testing
9) What are the limitations of selenium?
Selenium has following limitations:
  • It can be used only to test web based application.
  • Mobile applications can not be tested using selenium.
  • You can not test captcha and bar code by using selenium.
  • The user must have the knowledge of programming language for using selenium.
  • Reports can only be generated using third party tools like TestNG or Junit.
10) What is selenese?
Selenese is a lanuage which is used for writing test script in selenium IDE.
11) Describe the different types of locators in Selenium?
Locator is an address which identifies a web element uniquely within the web page.
There are different types of locators in Selenium to identify web elements accurately and precisely.
These are:
  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector
  • DOM
12) What is an Xpath?
Xpath is used to locate a web element based on its XML path. It can be used to locate HTML elements.
13) Which is the latest Selenium tool?
The latest Selenium tool is WebDriver.
14) What are the different types of Drivers that WebDriver contains?
These are the different drivers available in WebDriver:
  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver
15) What is Selenium Grid?
Selenium Grid facilitates you to distribute your tests on multiple machines and all of them at the same time. So, you can execute tests on Internet Explorer on Windows and Safari on Mac machine using the same text script. It reduces the time of test execution and provides quick feedback.
16) Where the result is seen of Test Execution in Selenium IDE?
The result of test execution is displayed in a Log Window in Selenium IDE.
17) Can you edit tests in Selenium IDE?
Yes, tests in Selenium IDE can be edited. There are two ways to edit tests in Selenium IDE.
  • By Table views
  • Looking into the source code
18) Can you use html id and name while using Selenium IDE?
Yes, You can use html id and name as it is available in Selenium IDE.
19) What are the WebDriver supported Mobile Testing Drivers?
WebDriver supported “mobile testing drivers” are:
  • AndroidDriver
  • IphoneDriver
  • OperaMobileDriver
20) What are the popular programming languages supported by Selenium WebDriver to write Test Cases?
  • JAVA
  • PHP
  • Python
  • C#
  • Ruby
  • Perl
21) What is the difference between assert and verify commands?
Assert: Assert command checks if the given condition is true or false. If the condition is true, the program control will execute the next phase of testing, and if the condition is false, execution will stop and nothing will be executed.
Verify: Verify command also checks if the given condition is true or false. It doesn’t halts program execution i.e. any failure during verification would not stop the execution and all the test phases would be executed.
22) What is the difference between “/” and “//” in Xpath?
Single Slash “/”: Single slash is used to create Xpath with absolute path.
Double Slash “//”: Double slash is used to create Xpath with relative path.
23) How to type in a text box using Selenium?
To type in a text box, we use sendKeys(“String to be entered”) to insert string in the text box.
Syntax:
  1. WebElement username = drv.findElement(By.id(“Email”));
  2. // entering username
  3. sendKeys(“sth”);
24) What is JUnit?
JUnit is an open source testing framework for java applications. It is introduced by Apache.
25) What are the four parameters that you need to pass in Selenium?
The four parameters that you have to pass in Selenium are:
  1. Host
  2. Port Number
  3. Browser
  4. URL
26) How can you “submit” a form using Selenium ?
  1. WebElement el  =  driver.findElement(By.id(“ElementID”));
  2. submit();
27) What is the difference between close() and quit()?
The close() method closes the current browser only whereas quit() method closes all browsers opened by WebDriver.
—————————————————————————————————————————————————-
Selenium interview questions with answers
  1. What is Selenium?
    Selenium is a suite of tools for browser automation. It is composed of “IDE”, a recording and playback mechanism, “WebDriver” and “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. It works with most browsers, including Firefox from 3.0 up to 7, Internet Explorer 8, Google Chrome, Safari and Opera 11.52.    Describe technical problems that you had with Selenium tool?
    As with any other type of test automation tools like SilkTest, HP QTP, Watir, 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.3.    What test can Selenium do?
    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.4.    What is the price of Selenium license per server?
    Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without charge.5.    How much does Selenium license cost per client machine?
    Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without charge.
    6.    Where to download Selenium?
    Selenium can be downloaded and installed for free from seleniumhq.org
    7.    What is the latest version of Selenium?
    The latest versions are Selenium IDE 1.3.0, Selenium Server (formerly the Selenium RC Server) 2.8.0, Selenium Client Drivers Java 2.8.0, Selenium Client Drivers C# 2.8.0, Selenium Client Drivers Ruby 2.8.0, Selenium Client Drivers Python 2.8.1, Selenium Grid 1.0.8.
    8.    What is Selenium IDE?
    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
    9.    What are the limitations of Selenium IDE?
    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.
    10.    What does SIDE stand for?
    Selenium IDE. It was a very tricky interview question.
    11.    What is Selenium Remote Control (RC) tool?
    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.
    12.    What are the advantages using Selenium as testing tool?
    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.
    13.    What is Selenium Grid?
    Selenium Grid extends Selenium RC to distribute your tests across multiple servers, saving you time by running tests in parallel.
    14.    What is Selenium WebDriver?
    Selenium WebDriver is a tool for writing automated tests of websites. It is an API name and aims to mimic the behaviour 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.
    15.    How many browsers are supported by Selenium IDE?
    Test Engineer can record and playback test with Selenium IDE in Firefox.
    16.    Can Selenium test an application on iPhone’s Mobile Safari browser?
    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.
    17.    Can Selenium test an application on Android browser?
    Selenium should be able to handle Android browser. There is experimental Selenium Android Driver for running tests in Android browser.
    18.    What are the disadvantages of using Selenium as testing tool?
    Selenium weak points are tricky setup; dreary errors diagnosis; tests only web applications
    19.    How many browsers are supported by Selenium Remote Control?
    QA Engineer can use Firefox 7, IE 8, Safari 5 and Opera 11.5 browsers to run actuall tests in Selenium RC.
    20.    How many programming languages can you use in Selenium RC?
    Several programming languages are supported by Selenium Remote Control – C# Java Perl PHP Python Ruby
    21.    How many testing framework can QA Tester use in Selenium RC?
    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).
    22.    How to developer Selenium Test Cases?
    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.
    23.    What programming language is best for writing Selenium tests?
    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.
    24.    Have you read any good books on Selenium?
    There are several great books covering Selenium automation tool, you could check the review at Best Selenium Books: Top Recommended page
    25.    Do you know any alternative test automation tools for Selenium?
    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.
    26.    Compare HP QTP vs Selenium?
    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. Read Selenium vs QTP comparison
    27.    Compare Borland Silktest vs Selenium?
    Check Selenium vs SilkTest comparison
    28.    How to test Ajax application with Selenium
    Ajax interview questions could be tough for newbie in the test automation, but will be easily cracked by Selenium Tester with a relevant experience. Read the detailed approach at Testing Ajax applications with Selenium in the right way
    29.    How can I learn to automate testing using Selenium?
    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. I hope this Selenium tutorial will be helpful in the preparation for this Selenium interview question.
    30. What are the main components of Selenium testing tools?
    Selenium IDE, Selenium RC and Selenium Grid
    31. What is Selenium IDE?
    Selenium IDE is for building Selenium test cases. It operates as a Mozilla Firefox add on and provides an easy to use interface for developing and running individual test cases or entire test suites. Selenium-IDE has a recording feature, which will keep account of user actions as they are performed and store them as a reusable script to play back.
    32. What is the use of context menu in Selenium IDE?
    It allows the user to pick from a list of assertions and verifications for the selected location.
    33. Can tests recorded using Selenium IDE be run in other browsers?
    Yes. Although Selenium IDE is a Firefox add on, however, tests created in it can also be run in other browsers by using Selenium RC (Selenium Remote Control) and specifying the name of the test suite in command line.
    34. What are the advantage and features of Selenium IDE?
    a. Intelligent field selection will use IDs, names, or XPath as needed
    b. It is a record & playback tool and the script format can be written in various languages including C#, Java, PERL, Python, PHP, HTML
    c. Auto complete for all common Selenium commands
    d. Debug and set breakpoints
    e. Option to automatically assert the title of every page
    f. Support for Selenium user-extensions.js file
    35. What are the disadvantage of Selenium IDE tool?
    a. Selenium IDE tool can only be used in Mozilla Firefox browser.
    b. It is not playing multiple windows when we record it.
    36. What is Selenium RC (Remote Control)?
    Selenium RC allows the test automation expert to use a programming language for maximum flexibility and extensibility in developing test logic. For example, if the application under test returns a result set and the automated test program needs to run tests on each element in the result set, the iteration / loop support of programming language’s can be used to iterate through the result set, calling Selenium commands to run tests on each item. Selenium RC provides an API and library for each of its supported languages. This ability to use Selenium RC with a high level programming language to develop test cases also allows the automated testing to be integrated with the project’s automated build environment.
    37. What is Selenium Grid?
    Selenium Grid in the selenium testing suit allows the Selenium RC solution to scale for test suites that must be run in multiple environments. Selenium Grid can be used to run multiple instances of Selenium RC on various operating system and browser configurations.
    38. How Selenium Grid works?
    Selenium Grid sent the tests to the hub. Then tests are redirected to an available Selenium RC, which launch the browser and run the test. Thus, it allows for running tests in parallel with the entire test suite.
    39. What you say about the flexibility of Selenium test suite?
    Selenium testing suite is highly flexible. There are multiple ways to add functionality to Selenium framework to customize test automation. As compared to other test automation tools, it is Selenium’s strongest characteristic. Selenium Remote Control support for multiple programming and scripting languages allows the test automation engineer to build any logic they need into their automated testing and to use a preferred programming or scripting language of one’s choice.
    Also, the Selenium testing suite is an open source project where code can be modified and enhancements can be submitted for contribution.
    40. What test can Selenium do?
    Selenium is basically used for the functional testing of web based applications. It can be used for testing in the continuous integration environment. It is also useful for agile testing
    41. What is the cost of Selenium test suite?
    Selenium test suite a set of open source software tool, it is free of cost.
    42. What browsers are supported by Selenium Remote Control?
    The test automation expert can use Firefox, IE 7/8, Safari and Opera browsers to run tests in Selenium Remote Control.
    43. What programming languages can you use in Selenium RC?
    C#, Java, Perl, PHP, Python, Ruby
    44. What are the advantages and disadvantages of using Selenium as testing tool?
    Advantages: Free, Simple and powerful DOM (document object model) level testing, can be used for continuous integration; great fit with Agile projects.
    Disadvantages: Tricky setup; dreary errors diagnosis; can not test client server applications.
    45. What is difference between QTP and Selenium?
    Only web applications can be testing using Selenium testing suite. However, QTP can be used for testing client server applications. Selenium supports following web browsers: Internet Explorer,
    Firefox, Safari, Opera or Konqueror on Windows, Mac OS X and Linux. However, QTP is limited to Internet Explorer on Windows.
    QTP uses scripting language implemented on top of VB Script. However, Selenium test suite has the flexibility to use many languages like Java, .Net, Perl, PHP, Python, and Ruby.
    46. What is difference between Borland Silk test and Selenium?
    Selenium is completely free test automation tool, while Silk Test is not. Only web applications can be testing using Selenium testing suite. However, Silk Test can be used for testing client server applications. Selenium supports following web browsers: Internet Explorer, Firefox, Safari, Opera or Konqueror on Windows, Mac OS X and Linux. However, Silk Test is limited to Internet Explorer and Firefox.
    Silk Test uses 4Test scripting language. However, Selenium test suite has the flexibility to use many languages like Java, .Net, Perl, PHP, Python, and Ruby.
    47. What is the difference between an assert and a verify with Selenium commands?
    Effectively an “assert” will fail the test and abort the current test case, whereas a “verify” will fail the test and continue to run the test case.
    48. If a Selenium function requires a script argument, what would that argument look like in general terms?
    StoreEval(script, variable) and storeExpression(expression, variableName)
    49. If a Selenium function requires a pattern argument, what five prefixes might that argument have?
    glob, regexp, exact, regexpi
    50. What is the regular expression sequence that loosely translates to “anything or nothing?”
    (.* i.e., dot star) This two-character sequence can be translated as “0 or more occurrences of any character” or more simply, “anything or nothing.
    51. What is the globbing sequence that loosely translates to “anything or nothing?
    (*) which translates to “match anything,” i.e., nothing, a single character, or many characters.
    52. What does a character class for all alphabetic characters and digits look like in regular expressions?
    [0-9] matches any digit
    [A-Za-z0-9] matches any alphanumeric character
    [A-Za-z] matches any alphabet character
    53. What does a character class for all alphabetic characters and digits look like in globbing?
    [0-9] matches any digit
    [a-zA-Z0-9] matches any alphanumeric character
    [a-zA-Z] matches any alphabet character
    54. What must one set within SIDE in order to run a test from the beginning to a certain point within the test?
    Set Toggle BreakPoint.
    55. What does a right-pointing green triangle at the beginning of a command in SIDE indicate?
    Play Entire Test Suite
    56. Which wildcards does SIDE support?
    *, [ ]
    57. What are the four types of regular expression quantifiers which we’ve studied?
    Ans : * quantifier: 0 or more of the preceding character (or group)
    + quantifier: 1 or more of the preceding character (or group)
    ? quantifier: 0 or 1 of the preceding character (or group)
    {1,5} quantifier: 1 through 5 of the preceding character (or group)
    58. What regular expression special character(s) means “any character?”
    (.*)
    59. What distinguishes between an absolute and relative URL in SIDE?
    Absolute URL: Its is base url and this represent domain address.
    Relative URL: (Absolute URL + Page Path).
    Open command uses Base URL (Absolute URL) to navigate web page.
    60. How would one access a Selenium variable named “count” from within a JavaScript snippet?
    ${count}
    61. What Selenese command can be used to display the value of a variable in the log file, which can be very valuable for debugging?
    echo()
    62. If one wanted to display the value of a variable named answer in the log file, what would the first argument to the previous command look like?
    echo()
    63. Which Selenium command(s) simulates selecting a link?
    click, clickandWait, ClickAt, ClickAtandWait, DoubleClick, DoubleClickandWait, doubleClickAt, doubleClickAtandWait
    64. Which two commands can be used to check that an alert with a particular message popped up?
    The following commands are available within Selenium for processing Alerts:
    • getAlert()
    • assertAlert()
    • assertAlertNotPresent()
    • assertAlertPresent()
    • storeAlert()
    • storeAlertPresent()
    • verifyAlert()
    • verifyAlertNotPresent()
    • verifyAlertPresent()
    • waitForAlert()
    • waitForAlertNotPresent()
    • waitForAlertPresent()
    The AlertPresent() and AlertNotPresent() functions check for the existence or not of an alert – regardless of it’s content. The Alert() functions allow the caller to specify a pattern which should be matched. The getAlert() method also exists in Selenium RC, and returns the text from the previous Alert displayed.
Selenium Interview Questions with Answers
Q1. What are the annotations used in TestNG ?
Ans-  @Test, @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass, @BeforeMethod, @AfterMethod.
Q2. How do you read data from excel ?
Ans-      FileInputStream fis = new FileInputStream(“path of excel file”);
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(“sheetName”);
String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue();
Q3. What is the use of xpath ?
Ans- it is used to find the WebElement in web page. It is very useful to identify the dynamic web elements.
Q4. What are different types of locators ?
Ans-  There are 8 types of locators and all are the static methods of the By class.
By.id(), By.name(), By.tagName(), By.className(), By.linkText(), By.partialLinkText(),By.xpath,  By.cssSelector().
Q5. What is the difference between Assert and Verify?
Ans- Assert- it is used to verify the result. If the test case fail then it will stop the execution of the test case there itself and move the control to other test case.
Verify- it is also used to verify the result. If the test case fail then it will not stop the execution of that test case.
Q6. What is the alternate way to click on login button?
Ans- use submit() method but it can be used only when attribute type=submit.
Q7. How do you verify if the checkbox/radio is checked or not ?
Ans- We can use isSelected() method.
Syntax –
driver.findElement(By.xpath(“xpath of the checkbox/radio button”)).isSelected();
If the return value of this method is true then it is checked else it is not.
Q8. How do you handle alert pop-up ?
Ans- To handle alert pop-ups, we need to 1st switch control to alert pop-ups then click on ok or cancle then move control back to main page.
Syntax-
String mainPage = driver.getWindowHandle();
Alert alt = driver.switchTo().alert(); → to move control to alert popup
alt.accept(); —> to click on ok.
alt.dismiss(); —> to click on cancle.
Then move the control back to main web page-
driver.switchTo().window(mainPage); → to switch back to main page.
Q9. How do you launch IE/chrome browser?
Ans- Before launching IE or Chrome browser we need to set the System property.
To open IE browser → System.setProperty(“webdriver.ie.driver”,”path of theiedriver.exe file ”);
WebDriver driver = new InternetExplorerDriver();
To open Chrome browser → System.setProperty(“webdriver.chrome.driver”,”path of the chromeDriver.exe file ”);
WebDriver driver = new ChromeDriver();
Q10. How to perform right click using WebDriver?
Ans- use Actions class.
Actions act = new Actions(driver); // where driver is WebDriver type
act.moveToElement(webElement).perform();
act.contextClick().perform();
Q11. How do perform drag and drop using WebDriver?
Ans- use Action class.
Actions act = new Actions(driver);
WebElement source = driver.findElement(By.xpath(“ —–”)); //source ele which you want to drag
WebElement target = driver.findElement(By.xpath(“ —–”)); //target where you want to drop
act.dragAndDrop(source,target).perform();
Q12. Give the example for method overload in WebDriver.
Ans- frame(string), frame(int), frame(WebElement).
Q13. How do you upload a file?
Ans- To upload a file we can use sendKeys() method.
Syntax – driver.findElement(By.xpath(“input field”)).sendKeys(“path of the file which u want to upload”);
Q14. How do you click on a menu item in a drop down menu?
Ans- if that menu has been created by using select tag then we can use the methods selectByValue() or selectByIndex() or selectByVisibleText(). These are the methods of the Select class.
If the menu has not been created by using the select tag then we can simply find the xpath of that element and click on that to select.
Q15. How do you simulate browser back and forward ?
Ans- driver.navigate().back();
driver.navigate().forward();
Q16. How do you get the current page URL ?
Ans- driver.getCurrentUrl();
Q17. What is the difference between ‘/’ and ‘//’ ?
Ans-    //- it is used to search in the entire structure.
/- it is used to identify the immediate child.
Q18. What is the difference between findElement and findElements?
Ans- Both methods are abstract method of WebDriver interface and used to find the WebElement in a web page.
findElement() –  it used to find the one web element. It return only one WebElement type.
findElements()-  it used to find more than one web element. It return List of  WebElements.
Q19. How do you achieve synchronization in WebDriver ?
Ans- We can use implicit wait.
Syntax- driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Here it will wait for 10sec if while execution driver did not find the element in the page immediately. This code will attach with each and every line of the script automatically. It is not required to write everytime. Just write it once after opening the browser.
Q20. Write the code for Reading and Writing to Excel through Selenium ?
Ans-     FileInputStream fis = new FileInputStream(“path of excel file”);
Workbook wb          = WorkbookFactory.create(fis);
Sheet s                     = wb.getSheet(“SheetName”);
String value             = s.getRow(rowNum).getCell(cellNum).getStringCellValue();  // read data
s.getRow(rowNum).getCell(cellNum).setCellValue();                                               //write data
FileOutputStream fos = new FileOutputStream(“path of file”);
wb.write(fos);                                                                                                             //save file
Q21. How to get typed text from a textbox ?
Ans- use getAttribute(“value”) method by passing arg as value.
syntax-  String typedText  = driver.findElement(By.xpath(“xpath of box”)).getAttribute(“value”));
Q22. What are the different exceptions you got when working with WebDriver ?
Ans- ElementNotVisibleException, ElementNotSelectableException, NoAlertPresentException, NoSuchAttributeException, NoSuchWindowException, TimeoutException, WebDriverException etc.
Q23. What are the languages supported by WebDriver ?
Ans- Python, Ruby, C# and Java are all supported directly by the development team. There are also webdriver implementations for PHP and Perl.
Q24. How do you clear the contents of a textbox in selenium ?
Ans- use clear() method.
syntax-  driver.findElement(By.xpath(“xpath of box”)).clear();
Q25. What is a Framework ?
Ans- A framework is  set of automation guidelines  which help in
Maintaining consistency of Testing, Improves test structuring, Minimum usage of code, Less Maintenance of code, Improve re-usability, Non Technical testers can be involved in code, Training period of using the tool can be reduced,  Involves Data wherever appropriate.
There are five types of framework used in software automation testing:
1-Data Driven Automation Framework
2-Method Driven Automation Framework
3-Modular Automation Framework
4-Keyword Driven Automation Framework
5-Hybrid Automation Framework , its basically combination of different frameworks. (1+2+3).
Q26. What are the prerequisites to run selenium webdriver?
Ans- JDK, Eclipse, WebDriver(selenium standalone jar file), browser, application to be tested.
Q27. What are the advantages of selenium webdriver?
Ans- a) It supports with most of the browsers like Firefox, IE, Chrome, Safari, Opera etc.
b)  It supports with most of the language like Java, Python, Ruby, C# etc.
b) Doesn’t require to start server before executing the test script.
c) It has actual core API which has binding in a range of languages.
d) It supports of moving mouse cursors.
e) It support to test iphone/Android applications.
Q28. What is WebDriverBackedSelenium ?
Ans- WebDriverBackedSelenium is a kind of class name where we can create an object for it as below: Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, “URL path of website”).
The main use of this is when we want to write code using both WebDriver and Selenium RC , we must use above created object to use selenium commands.
Q29. How to invoke an application in webdriver ?
Ans- driver.get(“url”); or driver.navigate().to(“url”);
Q30. What is Selenium Grid ?
Ans- Selenium-Grid allows you to run your tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines, different browsers and operating systems. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.
Q31. How to get the number of frames on a page ?
Ans- List <WebElement> framesList = driver.findElements(By.xpath(“//iframe”));
int numOfFrames = frameList.size();
Q32. How do you simulate scroll down action ?
Ans- use java script to scroll down-
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript(“window.scrollBy(0,4500)”, “”); //scroll down, value 4500 you can change as per your req
jsx.executeScript(“window.scrollBy(450,0)”, “”); //scroll up
ex-
public class ScrollDown {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“http://www.flipkart.com/womens-clothing/pr?sid=2oq,c1r&otracker=hp_nmenu_sub_women_1_View%20all&#8221;);
driver.manage().window().maximize();
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript(“window.scrollBy(0,4500)”, “”); //scroll down
Thread.sleep(3000);
jsx.executeScript(“window.scrollBy(450,0)”, “”); //scroll up
}
}
Q33. What is the command line we have to write inside a .bat file to execute a selenium project when we are     using testng ?
Ans- java -cp bin;jars/* org.testng.TestNG testng.xml
Q34. Which  is the package which is to be imported while working with WebDriver ?
Ans- org.openqa.selenium
Q35. How to check if an element is visible on the web page ?
Ans- use isDisplayed() method. The return type of the method is boolean. So if it return true then element is     visible else not visible.
Syntax – driver.findElement(By.xpath(“xpath of elemnt”)).isDisplayed();
Q36. How to check if a button is enabled on the page ?
Ans- use isEnabled() method. The return type of the method is boolean. So if it return true then button is     enabled else not enabled.
Syntax – driver.findElement(By.xpath(“xpath of button”)).isEnabled();
Q37. How to check if a text is highlighted on the page ?
Ans- To identify weather color for a field is different or not-
String color = driver.findElement(By.xpath(“//a[text()=’Shop’]”)).getCssValue(“color”);
String backcolor = driver.findElement(By.xpath(“//a[text()=’Shop’]”)).getCssValue(“background-color”);
System.out.println(color);
System.out.println(backcolor);
Here if both color and backcolor different then that means that element is in different color.
Q38. How to check the checkbox or radio button is selected ?
Ans- use  isSelected() method to identify. The return type of the method is boolean. So if it return true then         button is selected else not enabled.
Syntax – driver.findElement(By.xpath(“xpath of button”)).isSelected();
Q39. How to get the title of the page ?
Ans- use getTitle() method.
Syntax- driver.getTitle();
Q40. How do u get the width of the textbox ?
Ans-     driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth();
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight();
Q41. How do u get the attribute of the web element ?
Ans- driver.getElement(By.tagName(“img”)).getAttribute(“src”) will give you the src attribute of this tag.     Similarly, you can get the values of attributes such as title, alt etc.
Similarly you can get CSS properties of any tag by using getCssValue(“some propety name”).
Q42. How to check whether a text is underlined or not ?
Ans- Identify by getCssValue(“border-bottom”) or sometime getCssValue(“text-decoration”) method if the
cssValue is ‘underline’ for that WebElement or not.
ex- This is for when moving cursor over element that is going to be underlined or not-
public class UnderLine {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.google.co.in/?gfe_rd=ctrl&ei=bXAwU8jYN4W6iAf8zIDgDA&gws_rd=cr&#8221;);
String cssValue= driver.findElement(By.xpath(“//a[text()=’Hindi’]”)).getCssValue(“text-decoration”);
System.out.println(“value”+cssValue);
Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.xpath(“//a[text()=’Hindi’]”))).perform();
String cssValue1= driver.findElement(By.xpath(“//a[text()=’Hindi’]”)).getCssValue(“text-decoration”);
System.out.println(“value over”+cssValue1);
driver.close();
}
}
Q43. How to change the URL on a webpage using selenium web driver ?
Ans-  driver.get(“url1”);
driver.get(“url2”);
Q44. How to hover the mouse on an element ?
Ans- Actions act = new Actions(driver);
act.moveToElement(webelement); //webelement on which you want to move cursor
Q45. What is the use of getOptions() method ?
Ans- getOptions() is used to get the selected option from the dropdown list.
Q46. What is the use of deSelectAll() method ?
Ans- It is used to deselect all the options which have been selected from the dropdown list.
Q47. Is WebElement an interface or a class ?
Ans- WebDriver is an Interface.
Q48. FirefoxDriver is class or an interface and from where is it inherited ?
Ans- FirefoxDriver is a class. It implements all the methods of  WebDriver interface.
Q49. Which is the super interface of webdriver ?
Ans- SearchContext.
Q50. What is the difference b/w close() and quit()?
Ans- close() – it will close the browser where the control is.
quit()  – it will close all the browsers opened by WebDriver.
Q51. How to enter text without using sendkeys() ?
Ans – Yes we can enter text without using sendKeys() method. We have to use combination of javascript and wrapper classes with WebDriver extension class, check the below code-
public static void setAttribute(WebElement element, String
attributeName, String value)
{
WrapsDriver wrappedElement = (WrapsDriver) element;
JavascriptExecutor driver = (JavascriptExecutor)
wrappedElement.getWrappedDriver();
driver.executeScript(“arguments[0].setAttribute(arguments[1],
arguments[2])”, element, attributeName, value);
}
call the above method in the test script and pass the text field attribute and pass the text you want to enter.
Q52. There is a scenario whenever “Assert.assertEquals()” function fails automatically it has to take screenshot. How can you achieve this ?
Ans- By using EventFiringWebDriver.
Syntax-
EventFiringWebDriver eDriver=new EventFiringWebDriver(driver);
File srcFile = eDriver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File(imgPath));
Q53. How do you handle https website in selenium
Ans- By changing the setting of FirefoxProfile.
Syntax-
public class HTTPSSecuredConnection {
public static void main(String[] args){
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(false);
WebDriver driver = new FirefoxDriver(profile);
driver.get(“url”);
}
}
Q54. How to login into any site if its showing any authetication popup for user name and pass ?
Ans – pass the username and password with url.
Syntax- http://username:password@url
ex- http://creyate:jamesbond007@alpha.creyate.com
Q55. What is the name of Headless browser.
Ans- HtmlUnitDriver.
Q56. Open a browser in memory means whenever it will try to open a browser the browser page must not come and can perform the operation internally.
Ans- use HtmlUnitDriver.
ex-
public class Memory {
public static void main(String[] args) {
HtmlUnitDriver driver = new HtmlUnitDriver(true);
driver.setJavascriptEnabled(false);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.google.co.in/&#8221;);
System.out.println(driver.getTitle());
}
}
Q57. What are the benefits of using TestNG?
Ans- 1- TestNG allows us to execute of test cases based on group.
2- In TestNG Annotations are easy to understand.
3-Parallel execution of Selenium test cases is possible in TestNG.
4- Three kinds of report generated
5- Order of execution can be changed
6- Failed test cases can be executed
7- Without having main function we can execute the test method.
8- An xml file can be generated to execute the entire test suite. In that xml file we can rearrange our execution order and we can also skip the execution of particular test case.
Q58. How do you take screen shot without using EventFiringWebDriver ?
Ans-
File srcFile = ((TakeScreenshot)driver).getScreenshotAs(OutputType.FILE); //now we can do anything with this screenshot
like copy this to any folder-
FileUtils.copyFile(srcFile,new File(“folder name where u want to copy/file_name.png”));
Q59. How do you send ENTER/TAB keys in webdriver?
Ans- use click() or submit() [submit() can be used only when type=’submit’]) method for ENTER.
Or act.sendKeys(Keys.ENTER);
For Tab-
act.sendKeys(Keys.TAB);
where act is Actions class type. ( Actions act = new Actions(act); )
Q60. What is Datadriven framework & Keyword Driven?
Ans-  Datadriven framework- In this Framework , while Test case logic resides in Test Scripts, the Test Data is separated and kept outside the Test Scripts.Test Data is read from the external files (Excel File) and are loaded into the variables inside the Test Script. Variables are used both for Input values and for Verification values.
Keyword Driven framework- The Keyword-Driven or Table-Driven framework requires the development of data tables and keywords, independent of the test automation tool used to execute them . Tests can be designed with or without the Application. In a keyword-driven test, the functionality of the application-under-test is documented in a table as well as in step-by-step instructions for each test.
Q61. While explaining the framework, what are points which should be covered ?
Ans-    1.What is the frame work.
2. Which frame work you are using.
3. Why This Frame work.
4. Architecture.
5. Explanation of every component of frame work.
6. Process followed in frame work.
7. How & when u execute the frame work.
8. Code (u must write code and explain).
9. Result and reporting .
10. You should be able to explain it for 20 Minutes.
Q62. How to switch back from a frame ?
Ans- use method defaultContent().
Syntax – driver.switchTo().defaultContent();
Q63. How to type text in a new line inside a text area ?
Ans- Use \n for new line.
ex-  webelement.sendKeys(“Sanjay_Line1.\n Sanjay_Line2.”);
it will type in text box as
Sanjay_Line1.
Sanjay_Line2.
Q64. What is the use of AutoIt tool ?
Ans- Some times while doing testing with selenium, we get stuck by some interruptions like a window based pop up. But selenium fails to handle this as it has support for only web based application. To overcome this problem we need to use AutoIT along with selenium script. AutoIT is a third party tool to handle window based applications. The scripting language used is in VBScript.
Q65. How to perform double click using WebDriver ?
Ans- use doubleClick() method.
Syntax- Actions act = new Actions(driver);
act.doubleClick(webelement);
Q66. How to press Shift+Tab ?
Ans-     String press = Keys.chord(Keys.SHIFT,Keys.TAB);
webelement.sendKeys(press);
Q67. What is the use of contextClick() ?
Ans- It is used to right click.
Q68. What is the difference b/w getWindowHandles() and getWindowHandle() ?
Ans- getWindowHandles()- is used to get the address of all the open browser and its return type is Iterator<String>.
getWindowHandle()- is used to get the address of the current browser where the conrol is and return type is String.
Q69. How do you accommodate project specific methods in your framework ?
Ans- 1st go through all the manual test cases and identify the steps which are repeating. Note down such steps and make them as methods and write into ProjectSpecificLibrary.
Q70. What are different components of your framework ?
Ans- Library- Assertion, ConfigLibrary, GenericLibrary, ProjectSpecificLibrary, Modules.
Drivers folder, Jars folder, excel file.
Q71. What are the browsers supported by Selenium IDE ?
Ans-  Mozilla FireFox only. Its an Firefox add on.
Q72. What are the limitations of Selenium IDE ?
Ans- a)-  It does not supports looping or conditional statements. Tester has to use native languages to write logic in the test case.
b)-  It does not supports test reporting, you have to use selenium RC with some external reporting plugin like TestNG or JUint to get test execution report.
c)- Error handling is also not supported depending on the native language for this.
d) Only support in Mozilla FireFox only. Its an Firefox add on.
Q73. How to check all checkboxes in a page ?
Ans- List<webElement>  chkBox = driver.findElements(By.xpath(“//htmltag[@attbute=’checkbox’]”));
for(int i=0; i<=chkBox.size(); i++){
chkBox.get(i).click();
}
Q74. Count the number of links in a page.
Ans- use the locator By.tagName and find the elements for the tag //a then use loop to count the number of elements found.
Syntax-  int  count = 0;
List<webElement>  link = driver.findElements(By.tagName(“a”));
System.out.println(link.size());  // this will print the number of links in a page.
Q75. How do you identify the Xpath of element on your browser ?
And- to find the xpath , we use Firebug addons on firefox browser and to identify the xpath written we use Firepath addons.
Syntax- //htmltag[@attname=’attvalue’] or //html[text()=’textvalue’] or //htmltag[contains(text(),’textvalue’)] or //htmltag[contains(@attname,’attvalue’)]
Q76. What is Selenium Webdriver ?
Ans- WebDriver is the name of the key interface against which tests should be written in Java. All the methods of WebDriver have been implementated by RemoteWebDriver.
Q77. What is Selenium IDE
Ans- Selenium IDE is a complete integrated development environment (IDE) for Selenium tests. It is implemented as a Firefox Add-On, and allows recording, editing, and debugging tests. It was previously known as Selenium Recorder.
Scripts may be automatically recorded and edited manually providing autocompletion support and the ability to move commands around quickly.
Scripts are recorded in Selenese, a special test scripting language for Selenium. Selenese provides commands for performing actions in a browser (click a link, select an option), and for retrieving data from the resulting pages.
Q78. What are the flavors of selenium ?
Ans- selenium IDE, selenium RC, Selenium WebDriver and Selenium Grid.
Q79. What is selenium ?
Ans- Its an open source Web Automation Tool. It supports all types of web browsers. Despite being open source its actively developed and supported.
Q80. Advantages of selenium over other tools ?
Ans- 1) Its free of cost,
it supports many languages like Java, C#, Ruby, Python etc.,
it allows simple and powerful DOM-level testing etc.
Q81. What is main difference between RC and webdriver ?
Ans- Selenium RC injects javascript function into browsers when the web page is loaded.
Selenium WebDriver drives the browser using browser’s built-in support.
Q82. Why you choose webdriver over RC ?
Ans-  1) Native automation faster and a little less prone to error and browser configuration,
2) Does not Requires Selenium-RC Server to be running
3) Access to headless HTMLUnitDriver can allow really fast tests
4) Great API etc.
Q83. Which one is better xpath or CSS ?
Ans- xpath.
Q84. How will you handle dynamic elements ?
Ans- By writing relative xpath.
Q85. what are the different assertions or check points used in your script?
Ans- The common types of validations are:
a)  Is the page title as expected
b) Validations against an element on the page
c)  Does text exist on the page
d) Does a javascript call return an expected value
method used for validation – Assert.assertEquals();
Q86. What is actions class in webdriver?
Ans- Actions class is used to control the actions of mouse.
Q87. What is the difference between before method and before class ?
Ans- @BeforeMethod- this will execute before every @Test method.
@BeforeClass- this will execute before every class.
Q88. What are the different attributes for @Test annotation?
Ans-  alwaysRun, dataProvider, dependsOnMethods, enabled, expectedExceptions, timeOut etc.
ex- @Test(expectedExceptions = ArithmeticException.class),
@Test(timeOut = 2000).
Q89. Can we run group of test cases using TestNG ?
Ans- yes.
Q90. What is object repository ?
Ans- An object repository is a very essential entity in any UI automation tool. A repository allows a tester to store all the objects that will be used in the scripts in one or more centralized locations rather than letting them be scattered all over the test scripts. The concept of an object repository is not tied to WET alone. It can be used for any UI test automation. In fact, the original reason why the concept of object repositories were introduced was for a framework required by QTP.
Q91. What are oops concepts ?
Ans- a) Encapsulation, b) Abstraction, c)Polymorphism, d) Inheritance.
Q92. What is inheritance ?
Ans- Inherit the feature of any class by making some relations between the class/interface is known as inheritance.
Q93. What is difference between overload and override ?
Ans- The methods by passing different arguments list/type is known as overloading of methods while having the same method signature with different method body is known as method overriding.
Q94. Does java supports multiple inheritance?
Ans- Interface supports multiple inheritance but class does not support.
Q95. Write a java program for swapping of two numbers ?
Ans- public class Swapping{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println(“enter the 1st num”);
int a = in.nextInt();
System.out.println(“enter the 2nd num”);
int b = in.nextInt();
System.out.println(“before swapping a=”+a+” and b= ”+b);
int x = a;
a = b;
b = x;
System.out.println(“After swapping a=”+a+” and b= ”+b);
}
}
Q96. Write a java program for factorial of a given number.
Ans- public class Factorial{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println(“enter the num for which u want the factorial”);
int num = in.nextInt();
for(int i=num-1; i>0; i– ){
num = num*i;
}
System.out.println(num);
}
}
Q97. What are different access modifiers in Java ?
Ans- private, default, protected and public.
Q98. Why do we go for automation testing ?
Ans- Reasons-
a) Manual testing of all work flows, all fields, all negative scenarios is time and cost consuming.
b) It is difficult to test for multi lingual sites manually.
c) Automation does not require human intervention. We can run automated test unattended(Overnight).
d) Automation increases speed of test execution.
e) Automation helps increase test coverage.
f) Manual testing can become boring and hence error prone.
Q99.  What is testing strategy ?
Ans-  A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
Q100. write a code to make use of assert if my username is incorrect.
Ans- try{
Assert.assertEquals(expUserName, actUserName);
}catch(Exception e){
Syste.out.println(“name is invalid”);
}
————————————————————————————————————————————————–
Webdriver (Selenium ) Interview Questions and answers
Question 1: What is Selenium 2.0
Answer: Webdriver is open source automation tool for web application. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.
Question 2: What is cost of webdriver, is this commercial or open source.
Answer: selenium  is open source and free of cost.
Question 3: how you specify browser configurations with Selenium 2.0?
Answer:  Following driver classes are used for browser configuration
  • AndroidDriver,
  • ChromeDriver,
  • EventFiringWebDriver,
  • FirefoxDriver,
  • HtmlUnitDriver,
  • InternetExplorerDriver,
  • IPhoneDriver,
  • IPhoneSimulatorDriver,
  • RemoteWebDriver
Question 4: How is Selenium 2.0 configuration different than Selenium 1.0?
Answer: 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.
Question5: Can you show me one code example of setting Selenium 2.0?
Answer: below is example
WebDriver driver = new FirefoxDriver();
driver.findElement(By.cssSelector(“#gb_2 > span.gbts”)).click();
driver.findElement(By.cssSelector(“#gb_1 > span.gbts”)).click();
driver.findElement(By.cssSelector(“#gb_8 > span.gbts”)).click();
driver.findElement(By.cssSelector(“#gb_1 > span.gbts”)).click();
Question 6: Which web driver implementation is fastest?
Answer: 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
Question 7: What all different element locators are available with Selenium 2.0?
Answer: 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. className (“CalssName”));
driver.findElement(By. linkText (“LinkeText”));
driver.findElement(By. partialLinkText (“PartialLink”));
driver.findElement(By. tagName (“TanName”));
driver.findElement(By.xpath(“XPathLocator));
Question 8:  How do I submit a form using Selenium?
Answer:
WebElement el  =  driver.findElement(By.id(“ElementID”));
el.submit();
Question 9: How to capture screen shot in Webdriver?
Answer:
File file= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File(“c:\\name.png”));
Question 10: How do I clear content of a text box in Selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id(“ElementID”));
el.clear();
Question 11:  How to execute java scripts function.
Answer:
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript(“pass your java scripts”);
Question 12:  How to select a drop down value using Selenium2.0?
Answer: See point 16 in below post:
Question 13: How to automate radio button in Selenium 2.0?
Answer:
WebElement el = driver.findElement(By.id(“Radio button id”));
//to perform check operation
el.click()
//verfiy to radio button is check it return true if selected else false
el.isSelected()
Question 14: How to capture element image using Selenium 2.0?
Question 15: How to count total number of rows of a table using Selenium 2.0?
Answer: 
List {WebElement} rows = driver.findElements(By.className(“//table[@id=’tableID’]/tr”));
int totalRow = rows.size();
Question 16:  How to capture page title using Selenium 2.0?
Answer:
String title =  driver.getTitle()
Question 17:  How to store page source using Selenium 2.0?
Answer:
String pagesource = driver.getPageSource()
Question 18: How to store current url using selenium 2.0?
Answer:
String currentURL  = driver.getCurrentUrl()
Question 19: How to assert text assert text of webpage using selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id(“ElementID”));
//get test from element and stored in text variable
String text = el.getText();
//assert text from expected
Assert.assertEquals(“Element Text”, text);
Question 20: How to get element attribute using Selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id(“ElementID”));
//get test from element and stored in text variable
String attributeValue = el. getAttribute(“AttributeName”) ;
Question 21: How to double click on element using selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id(“ElementID”));
Actions builder = new Actions(driver);
builder.doubleClick(el).build().perform();
Question 22: How to perform drag and drop in selenium 2.0?
Answer:
WebElement source  =  driver.findElement(By.id(“Source ElementID”));
WebElement destination  =  driver.findElement(By.id(“Taget ElementID”));
Actions builder = new Actions(driver);
builder.dragAndDrop(source, destination ).perform();

Question 23: How to maximize window using selenium 2.0?
Answer:
driver.manage().window().maximize();
—————————————————————————————————————————————————-
Ques 1) What are the annotations used in TestNG ?
Ans: @Test, @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass, @BeforeMethod, @AfterMethod.
Ques 2) How do you read data from excel ?
1
2
3
4
5
6
7
FileInputStream fis = new FileInputStream(“path of excel file”);
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(“sheetName”);
String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue();
Ques 3) What is the use of xpath ?
Ans- it is used to find the WebElement in web page. It is very useful to identify the dynamic web elements.
Ques 4) What are different types of locators ?
Ans- There are 8 types of locators and all are the static methods of the By class.
By.id(), By.name(), By.tagName(), By.className(), By.linkText(), By.partialLinkText(),By.xpath, By.cssSelector().
Ques 5) What is the difference between Assert and Verify?
Ans- Assert- it is used to verify the result. If the test case fail then it will stop the execution of the test case there itself and move the control to other test case.
Verify- it is also used to verify the result. If the test case fail then it will not stop the execution of that test case.
Ques 6) What is the alternate way to click on login button?
Ans- use submit() method but it can be used only when attribute type=submit.
Ques 7) How do you verify if the checkbox/radio is checked or not ?
Ans- We can use isSelected() method.
Syntax –
1driver.findElement(By.xpath(“xpath of the checkbox/radio button”)).isSelected();
If the return value of this method is true then it is checked else it is not.
Ques 8) How do you handle alert pop-up ?
Ans- To handle alert pop-ups, we need to 1st switch control to alert pop-ups then click on ok or cancle then move control back to main page.
Syntax-
1
2
3
4
5
6
7
8
9
10
11
String mainPage = driver.getWindowHandle();
Alert alt = driver.switchTo().alert(); // to move control to alert popup
alt.accept(); // to click on ok.
alt.dismiss(); // to click on cancel.
//Then move the control back to main web page-
driver.switchTo().window(mainPage); → to switch back to main page.
Ques 9) How do you launch IE/chrome browser?
Ans- Before launching IE or Chrome browser we need to set the System property.
1
2
3
4
5
//To open IE browser
System.setProperty(“webdriver.ie.driver”,”path of the iedriver.exe file ”);
WebDriver driver = new InternetExplorerDriver();
1
2
3
//To open Chrome browser → System.setProperty(“webdriver.chrome.driver”,”path of the chromeDriver.exefile ”);
WebDriver driver = new ChromeDriver();
Ques 10) How to perform right click using WebDriver?
Ans- Use Actions class
1
2
3
4
5
Actions act = new Actions(driver); // where driver is WebDriver type
act.moveToElement(webElement).perform();
act.contextClick().perform();
Ques 11) How do perform drag and drop using WebDriver?
Ans- Use Action class
1
2
3
4
5
6
7
Actions act = new Actions(driver);
WebElement source = driver.findElement(By.xpath(“ —–”)); //source ele which you want to drag
WebElement target = driver.findElement(By.xpath(“ —–”)); //target where you want to drop
act.dragAndDrop(source,target).perform();
Ques 12) Give the example for method overload in WebDriver.
Ans- frame(string), frame(int), frame(WebElement).
Ques 13) How do you upload a file?
Ans- To upload a file we can use sendKeys() method.
1driver.findElement(By.xpath(“input field”)).sendKeys(“path of the file which u want to upload”);
Ques 14) How do you click on a menu item in a drop down menu?
Ans- If that menu has been created by using select tag then we can use the methods selectByValue() or selectByIndex() or selectByVisibleText(). These are the methods of the Select class.
If the menu has not been created by using the select tag then we can simply find the xpath of that element and click on that to select.
Ques 15) How do you simulate browser back and forward ?
1
2
3
 driver.navigate().back();
driver.navigate().forward();
Ques 16) How do you get the current page URL ?
1driver.getCurrentUrl();
Ques 17) What is the difference between ‘/’ and ‘//’ ?
Ans- //- it is used to search in the entire structure.
/- it is used to identify the immediate child.
Ques 18) What is the difference between findElement and findElements?
Ans- Both methods are abstract method of WebDriver interface and used to find the WebElement in a web page.
findElement() – it used to find the one web element. It return only one WebElement type.
findElements()- it used to find more than one web element. It return List of WebElements.
Ques 19) How do you achieve synchronization in WebDriver ?
Ans- We can use implicit wait.
Syntax- driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Here it will wait for 10sec if while execution driver did not find the element in the page immediately. This code will attach with each and every line of the script automatically. It is not required to write every time. Just write it once after opening the browser.
Ques 20) Write the code for Reading and Writing to Excel through Selenium ?
1
2
3
4
5
6
7
8
9
10
11
12
13
FileInputStream fis = new FileInputStream(“path of excel file”);
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(“sheetName”);
String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue(); // read data
s.getRow(rowNum).getCell(cellNum).setCellValue(“value to be set”); //write data
FileOutputStream fos = new FileOutputStream(“path of file”);
wb.write(fos); //save file
Ques 21) How to get typed text from a textbox ?
Ans- use getAttribute(“value”) method by passing arg as value.
1String typedText = driver.findElement(By.xpath(“xpath of box”)).getAttribute(“value”));
Ques 22) What are the different exceptions you got when working with WebDriver ?
Ans- ElementNotVisibleException, ElementNotSelectableException, NoAlertPresentException, NoSuchAttributeException, NoSuchWindowException, TimeoutException, WebDriverException etc.
Ques 23) What are the languages supported by WebDriver ?
Ans- Python, Ruby, C# and Java are all supported directly by the development team. There are also webdriver implementations for PHP and Perl.
Ques 24) How do you clear the contents of a textbox in selenium ?
Ans- Use clear() method.
1driver.findElement(By.xpath(“xpath of box”)).clear();
Ques 25) What is a Framework ?
Ans- A framework is set of automation guidelines which help in
Maintaining consistency of Testing, Improves test structuring, Minimum usage of code, Less Maintenance of code, Improve re-usability, Non Technical testers can be involved in code, Training period of using the tool can be reduced, Involves Data wherever appropriate.
There are five types of framework used in software automation testing:
1-Data Driven Automation Framework
2-Method Driven Automation Framework
3-Modular Automation Framework
4-Keyword Driven Automation Framework
5-Hybrid Automation Framework , its basically combination of different frameworks. (1+2+3).
Ques 26) What are the prerequisites to run selenium webdriver?
Ans- JDK, Eclipse, WebDriver(selenium standalone jar file), browser, application to be tested.
Ques 27) What are the advantages of selenium webdriver?
Ans- a) It supports with most of the browsers like Firefox, IE, Chrome, Safari, Opera etc.
  1. b) It supports with most of the language like Java, Python, Ruby, C# etc.
  2. b) Doesn’t require to start server before executing the test script.
  3. c) It has actual core API which has binding in a range of languages.
  4. d) It supports of moving mouse cursors.
  5. e) It support to test iphone/Android applications.
Ques 28) What is WebDriverBackedSelenium ?
Ans- WebDriverBackedSelenium is a kind of class name where we can create an object for it as below:
1Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, “URL path of website”)
The main use of this is when we want to write code using both WebDriver and Selenium RC , we must use above created object to use selenium commands.
Ques 29) How to invoke an application in webdriver ?
1driver.get(“url”); or driver.navigate().to(“url”);
Ques 30) What is Selenium Grid ?
Ans- Selenium-Grid allows you to run your tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines, different browsers and operating systems. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.
Ques 31) How to get the number of frames on a page ?
1
2
3
List &lt;WebElement&gt; framesList = driver.findElements(By.xpath(“//iframe”));
int numOfFrames = frameList.size();
Ques 32) How do you simulate scroll down action ?
Ans- Use java script to scroll down-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript(“window.scrollBy(0,4500)”, “”); //scroll down, value 4500 you can change as per your req
jsx.executeScript(“window.scrollBy(450,0)”, “”); //scroll up
ex-
public class ScrollDown {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript(“window.scrollBy(0,4500)”, “”); //scroll down
Thread.sleep(3000);
jsx.executeScript(“window.scrollBy(450,0)”, “”); //scroll up
}
}
Ques 33) What is the command line we have to write inside a .bat file to execute a selenium project when we are using testng ?
Ans- java -cp bin;jars/* org.testng.TestNG testng.xml
Ques 34) Which is the package which is to be imported while working with WebDriver ?
Ans- org.openqa.selenium
Ques 35) How to check if an element is visible on the web page ?
Ans- use isDisplayed() method. The return type of the method is boolean. So if it return true then element is visible else not visible.
1driver.findElement(By.xpath(“xpath of elemnt”)).isDisplayed();
Ques 36) How to check if a button is enabled on the page ?
Ans- Use isEnabled() method. The return type of the method is boolean. So if it return true then button is enabled else not enabled.
1driver.findElement(By.xpath(“xpath of button”)).isEnabled();
Ques 37) How to check if a text is highlighted on the page ?
Ans- To identify weather color for a field is different or not-
1
2
3
4
5
6
7
String color = driver.findElement(By.xpath(“//a[text()=’Shop’]”)).getCssValue(“color”);
String backcolor = driver.findElement(By.xpath(“//a[text()=’Shop’]”)).getCssValue(“background-color”);
System.out.println(color);
System.out.println(backcolor);
Here if both color and back color different then that means that element is in different color.
Ques 38) How to check the checkbox or radio button is selected ?
Ans- Use isSelected() method to identify. The return type of the method is boolean. So if it return true then button is selected else not enabled.
1driver.findElement(By.xpath(“xpath of button”)).isSelected();
Ques 39) How to get the title of the page ?
Ans- Use getTitle() method.
1Syntax- driver.getTitle();
Ques 40) How do u get the width of the textbox ?
1
2
3
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth();
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight();
Ques 41) How do u get the attribute of the web element ?
Ans- driver.getElement(By.tagName(“img”)).getAttribute(“src”) will give you the src attribute of this tag. Similarly, you can get the values of attributes such as title, alt etc.
Similarly you can get CSS properties of any tag by using getCssValue(“some propety name”).
Ques 42) How to check whether a text is underlined or not ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Ans- Identify by getCssValue(“border-bottom”) or sometime getCssValue(“text-decoration”) method if the
cssValue is ‘underline’ for that WebElement or not.
ex- This is for when moving cursor over element that is going to be underlined or not-
public class UnderLine {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String cssValue= driver.findElement(By.xpath(“//a[text()=’Hindi’]”)).getCssValue(“text-decoration”);
System.out.println(“value”+cssValue);
Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.xpath(“//a[text()=’Hindi’]”))).perform();
String cssValue1= driver.findElement(By.xpath(“//a[text()=’Hindi’]”)).getCssValue(“text-decoration”);
System.out.println(“value over”+cssValue1);
driver.close();
}
}
Ques 43) How to change the URL on a webpage using selenium web driver ?
1
2
3
driver.get(“url1”);
driver.get(“url2”);
Ques 44) How to hover the mouse on an element ?
1
2
3
Actions act = new Actions(driver);
act.moveToElement(webelement); //webelement on which you want to move cursor
Ques 45) What is the use of getOptions() method ?
Ans- getOptions() is used to get the selected option from the dropdown list.
Ques 46) What is the use of deSelectAll() method ?
Ans- It is used to deselect all the options which have been selected from the dropdown list.
Ques 47) Is WebElement an interface or a class ?
Ans- WebDriver is an Interface.
Ques 48) FirefoxDriver is class or an interface and from where is it inherited ?
Ans- FirefoxDriver is a class. It implements all the methods of WebDriver interface.
Ques 49) Which is the super interface of webdriver ?
Ans- SearchContext.
Ques 50) What is the difference b/w close() and quit()?
Ans- close() – it will close the browser where the control is.
quit() – it will close all the browsers opened by WebDriver


Ques 1) Can we enter text without using sendKeys() ?
Ans – Yes we can enter text without using sendKeys() method. We have to use combination of javascript and wrapper classes with WebDriver extension class, check the below code-
1
2
3
4
5
6
7
8
9
10
11
public static void setAttribute(WebElement element, String attributeName, String value)
{
WrapsDriver wrappedElement = (WrapsDriver) element;
JavascriptExecutor driver = (JavascriptExecutor)wrappedElement.getWrappedDriver();
driver.executeScript(“arguments[0].setAttribute(arguments[1],arguments[2])”, element, attributeName, value);
}
call the above method in the test script and pass the text field attribute and pass the text you want to enter.
Ques 2) There is a scenario whenever “Assert.assertEquals()” function fails automatically it has to take screenshot. How can you achieve this ?
Ans- By using EventFiringWebDriver.
1
2
3
4
5
Syntax-EventFiringWebDriver eDriver=new EventFiringWebDriver(driver);
File srcFile = eDriver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File(imgPath));
Ques 3) How do you handle https website in selenium ?
Ans- By changing the setting of FirefoxProfile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Syntax-public class HTTPSSecuredConnection {
public static void main(String[] args){
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(false);
WebDriver driver = new FirefoxDriver(profile);
driver.get(“url”);
}
}
Ques 4) How to login into any site if its showing any authetication popup for user name and pass ?
Ans – pass the username and password with url.
1
2
3
Syntax- http://username:password@url
Ques 5) What is the name of Headless browser.
Ans- HtmlUnitDriver.
Ques 6) Open a browser in memory means whenever it will try to open a browser the browser page must not come and can perform the operation internally.
Ans- use HtmlUnitDriver.
ex-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Memory {
public static void main(String[] args) {
HtmlUnitDriver driver = new HtmlUnitDriver(true);
driver.setJavascriptEnabled(false);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println(driver.getTitle());
}
}
Ques 7) What are the benefits of using TestNG ?
Ans-
  1. a) TestNG allows us to execute of test cases based on group.
  2. b) In TestNG Annotations are easy to understand.
  3. c) Parallel execution of Selenium test cases is possible in TestNG.
  4. d) Three kinds of report generated
  5. e) Order of execution can be changed
  6. f) Failed test cases can be executed
  7. g) Without having main function we can execute the test method.
  8. h) An xml file can be generated to execute the entire test suite. In that xml file we can   rearrange our execution order and we can also skip the execution of particular test case.
Ques 8) How do you take screen shot without using EventFiringWebDriver ?
Ans-
1
2
3
4
5
File srcFile = ((TakeScreenshot)driver).getScreenshotAs(OutputType.FILE); //now we can do anything with this screenshot
like copy this to any folder-
FileUtils.copyFile(srcFile,new File(“folder name where u want to copy/file_name.png”));
Ques 9) How do you send ENTER/TAB keys in WebDriver ?
Ans- use click() or submit() [submit() can be used only when type=’submit’]) method for ENTER. Or use Actions class to press keys.
For Enter-
1act.sendKeys(Keys.RETURN);
For Tab-
1act.sendKeys(Keys.ENTER);
where act is Actions class type. ( Actions act = new Actions(driver); )
Ques 10) What is Datadriven framework & Keyword Driven ?
Ans- Datadriven framework- In this Framework , while Test case logic resides in Test Scripts, the Test Data is separated and kept outside the Test Scripts.Test Data is read from the external files (Excel File) and are loaded into the variables inside the Test Script. Variables are used both for Input values and for Verification values.
Keyword Driven framework- The Keyword-Driven or Table-Driven framework requires the development of data tables and keywords, independent of the test automation tool used to execute them . Tests can be designed with or without the Application. In a keyword-driven test, the functionality of the application-under-test is documented in a table as well as in step-by-step instructions for each test.
Ques 11) While explaining the framework, what are points which should be covered ?
Ans-
  1. a) What is the frame work.
  2. b) Which frame work you are using.
  3. c) Why This Frame work.
  4. d) Architecture.
  5. e) Explanation of every component of frame work.
  6. f) Process followed in frame work.
  7. g) How & when u execute the frame work.
  8. h) Code (u must write code and explain).
  9. i) Result and reporting .
  10. j) You should be able to explain it for 20 Minutes.
Ques 12) How to switch back from a frame ?
Ans- use method defaultContent().
1Syntax – driver.switchTo().defaultContent();
Ques 13) How to type text in a new line inside a text area ?
Ans- Use \n for new line.
1ex- webelement.sendKeys(“Sanjay_Line1.\n Sanjay_Line2.”);
it will type in text box as-
Sanjay_Line1.
Sanjay_Line2.
Ques 14) What is the use of AutoIt tool ?
Ans- Some times while doing testing with selenium, we get stuck by some interruptions like a window based pop up. But selenium fails to handle this as it has support for only web based application. To overcome this problem we need to use AutoIT along with selenium script. AutoIT is a third party tool to handle window based applications. The scripting language used is in VBScript.
Ques 15) How to perform double click using WebDriver ?
Ans- use doubleClick() method.
1
2
3
Syntax- Actions act = new Actions(driver);
act.doubleClick(webelement);
Ques 16) How to press Shift+Tab ?
Ans-
1
2
3
String press = Keys.chord(Keys.SHIFT,Keys.ENTER);
webelement.sendKeys(press);
Ques 17) What is the use of contextClick() ?
Ans- It is used to right click.
Ques 18) What is the difference b/w getWindowHandles() and getWindowHandle() ?
Ans- getWindowHandles()- is used to get the address of all the open browser and its return type is Iterator<String>.
getWindowHandle()- is used to get the address of the current browser where the conrol is and return type is String.
Ques 19) How do you accommodate project specific methods in your framework ?
Ans- 1st go through all the manual test cases and identify the steps which are repeating. Note down such steps and make them as methods and write into ProjectSpecificLibrary.
Ques 20) What are different components of your framework ?
Ans- Library- Assertion, ConfigLibrary, GenericLibrary, ProjectSpecificLibrary, Modules.
Drivers folder, Jars folder, excel file.
Ques 21) What are the browsers supported by Selenium IDE ?
Ans- Mozilla FireFox only. Its an Firefox add on.
Ques 22) What are the limitations of Selenium IDE ?
Ans-
  1. a) It does not supports looping or conditional statements. Tester has to use native languages to write logic in the test case.
  2. b) It does not supports test reporting, you have to use selenium RC with some external reporting plugin like TestNG or JUint to get test execution report.
  3. c) Error handling is also not supported depending on the native language for this.
  4. d) Only support in Mozilla FireFox only. Its an Firefox add on.
Ques 23) How to check all checkboxes in a page ?
Ans-
1
2
3
4
5
6
7
List&lt;webElement&gt; chkBox = driver.findElements(By.xpath(“//htmltag[@attbute=’checkbox’]”));
for(int i=0; i&lt;=chkBox.size(); i++){
chkBox.get(i).click();
}
Ques 24) Count the number of links in a page.
Ans- use the locator By.tagName and find the elements for the tag //a then use loop to count the number of elements found.
1
2
3
4
5
Syntax- int count = 0;
List&lt;webElement&gt; link = driver.findElements(By.tagName(“a”));
System.out.println(link.size()); // this will print the number of links in a page.
Ques 25) How do you identify the Xpath of element on your browser ?
And- to find the xpath , we use Firebug addons on firefox browser and to identify the xpath written we use Firepath addons.
1Syntax- //htmltag[@attname=’attvalue’] or //html[text()=’textvalue’] or //htmltag[contains(text(),’textvalue’)] or //htmltag[contains(@attname,’attvalue’)]
Ques 26) What is Selenium Webdriver ?
Ans- WebDriver is the name of the key interface against which tests should be written in Java. All the methods of WebDriver have been implementated by RemoteWebDriver.
Ques 27) What is Selenium IDE ?
Ans- Selenium IDE is a complete integrated development environment (IDE) for Selenium tests. It is implemented as a Firefox Add-On, and allows recording, editing, and debugging tests. It was previously known as Selenium Recorder.
Scripts may be automatically recorded and edited manually providing autocompletion support and the ability to move commands around quickly.
Scripts are recorded in Selenese, a special test scripting language for Selenium. Selenese provides commands for performing actions in a browser (click a link, select an option), and for retrieving data from the resulting pages.
Ques 28) What are the flavors of selenium ?
Ans- selenium IDE, selenium RC, Selenium WebDriver and Selenium Grid.
Ques 29) What is selenium ?
Ans- Its an open source Web Automation Tool. It supports all types of web browsers. Despite being open source its actively developed and supported.
Ques 30) Advantages of selenium over other tools ?
Ans-
  1. a) Its free of cost,
  2. b) it supports many languages like Java, C#, Ruby, Python etc.,
  3. c) it allows simple and powerful DOM-level testing etc.
Ques 31) What is main difference between RC and webdriver ?
Ans- Selenium RC injects javascript function into browsers when the web page is loaded.
Selenium WebDriver drives the browser using browser’s built-in support.
Ques 32) Why you choose webdriver over RC ?
Ans-
  1. a) Native automation faster and a little less prone to error and browser configuration,
  2. b) Does not Requires Selenium-RC Server to be running
  3. c) Access to headless HTMLUnitDriver can allow really fast tests
  4. d) Great API etc.
Ques 33) Which one is better xpath or CSS ?
Ans- xpath.
Ques 34) How will you handle dynamic elements ?
Ans- By writing relative xpath.
Ques 35) what are the different assertions or check points used in your script ?
Ans- The common types of validations are:
  1. a) Is the page title as expected,
  2. b) Validations against an element on the page,
  3. c) Does text exist on the page,
  4. d) Does a javascript call return an expected value.
1method used for validation – Assert.assertEquals();
Ques 36) What is actions class in WebDriver ?
Ans- Actions class is used to control the actions of mouse.
Ques 37) What is the difference between @BeforeMethod and @BeforeClass ?
Ans- @BeforeMethod- this will execute before every @Test method.
@BeforeClass- this will execute before every class.
Ques 38) What are the different attributes for @Test annotation ?
Ans- alwaysRun, dataProvider, dependsOnMethods, enabled, expectedExceptions, timeOut etc.
1
2
3
ex- @Test(expectedExceptions = ArithmeticException.class)
@Test(timeOut = 2000)
Ques 39) Can we run group of test cases using TestNG ?
Ans- yes.
Ques 40) What is object repository ?
Ans- An object repository is a very essential entity in any UI automation tool. A repository allows a tester to store all the objects that will be used in the scripts in one or more centralized locations rather than letting them be scattered all over the test scripts. The concept of an object repository is not tied to WET alone. It can be used for any UI test automation. In fact, the original reason why the concept of object repositories were introduced was for a framework required by QTP.
Ques 41) What are oops concepts ?
Ans-
  1. a) Encapsulation,
  2. b) Abstraction,
  3. c) Polymorphism,
  4. d) Inheritance.
Ques 42) What is inheritance ?
Ans- Inherit the feature of any class by making some relations between the class/interface is known as inheritance.
Ques 43) What is difference between overload and override ?
Ans- The methods by passing different arguments list/type is known as overloading of methods while having the same method signature with different method body is known as method overriding.
Ques 44) Does java supports multiple inheritance ?
Ans- Interface supports multiple inheritance but class does not support.
Ques 45) Write a java program for swapping of two numbers ?
Ans-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Swapping{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println(“enter the 1st num”);
int a = in.nextInt();
System.out.println(“enter the 2nd num”);
int b = in.nextInt();
System.out.println(“before swapping a=”+a+” and b= ”+b);
int x = a;
a = b;
b = x;
System.out.println(“After swapping a=”+a+” and b= ”+b);
}
}
Ques 46) Write a java program for factorial of a given number.
Ans-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Factorial{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println(“enter the num for which u want the factorial”);
int num = in.nextInt();
for(int i=num-1; i&gt;0; i– ){
num = num*i;
}
System.out.println(num);
}
}
Ques 47) What are the different access specifiers in Java?
Ans- private, default, protected and public.
Ques 48) Why do we go for automation testing ?
Ans- Reasons-
  1. a) Manual testing of all work flows, all fields, all negative scenarios is time and cost consuming.
  2. b) It is difficult to test for multi lingual sites manually.
  3. c) Automation does not require human intervention. We can run automated test unattended(Overnight).
  4. d) Automation increases speed of test execution.
  5. e) Automation helps increase test coverage.
  6. f) Manual testing can become boring and hence error prone.
Ques 49) What is testing strategy ?
Ans- A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
Ques 50) ) write a code to make use of assert if my username is incorrect.
Ans-
1
2
3
4
5
6
7
8
9
try{
Assert.assertEquals(expUserName, actUserName);
}catch(Exception e){
Syste.out.println(“name is invalid”);
}
—————————————————————————————————————————————————-
  • Why Java called platform independent?
JAVA is called as a platform independent programming language as it works on the principle “compile once, run everywhere”.
If you have written some code in JAVA and you have compiled that, you can execute the same code on any platform, the only thing you need is to install corresponding JVM(Java virtual machine).
  • What is the difference between an Interface and an Abstract class?
  1. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
  2. An abstract class is a class which may have the usual flavors of class members, but has some abstract methods.An interface has all public members and no implementation.
  • What is the purpose of garbage collection in Java?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program and reuse the resources again in the program.
  • What is HashMap and Map? and difference between them?
Map is Interface and Hashmap is class that implements Map.
HashMap allows null values as key and value whereas Hashtable doesnt allow.  HashMap is unsynchronized and Hashtable is synchronized.
  • State the significance of public, private, protected and default  access modifiers.
public : Public class is visible in other packages, field is visible everywhere.
private : Private Methods, variables are visible in same class and not avaialble in any other classs
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.
default :What you get by default ie, without any access modifier .It means that it is visible to all within a particular package.
  • What is Final in Java?
A final class can’t be extended
A final method can’t be overridden
A Final Variable can not be change.
  • What is an abstract class?
It serves as a template and it should be extend. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
  •  What is difference between Overloading and overwriting in Java?
Overloading
Method signature should not be same.
It happen at time of code compilation, so it called compile time polymorphism.
Method can have any return type.
Method can have any access level.
Overriding
Method signature should be same.
It happen on time of run time, so it called as run time polymorphism.
Method return type must be same as super class method
Method must have same or wide access level than super class method access level.

COMMONLY ASKED JAVA PROGRAMS IN SELENIUM INTERVIEW

In the recent past I visited couple of companies for interview during my job hunting. There I was asked to make some small java programs. And I believe that most of those programs we would have surely created during our graduation.
I am mentioning those small problems and programs here:
  1. Print below pattern:This program is one of the best to understand the for… loop
    1
    12
    123
    1234
    12345
public static void main( String[] args ) throws FileNotFoundException {
for( int i=1; i<=5; i++ ){
for( int j=1; j<=i; j++ ){
System.out.print ( j );
}
System.out.println (); //to print new line for each iteration of outer loop
}
}
  1. Print below pattern:This program is one of the best to understand the for… loop
    *
    ***
    *****
    *******
    *********
public static void main( String[] args ){
int p = 0;
for( int i=1; i<=5; i++ ){
for( int k=1; k<=5-i; k++ ){
System.out.print (” “);
}
for( int j=1; j<=i+p; j++ ){
System.out.print (“*”);
}
System.out.println ();
p=p+1;
}
}
  1. Program to read from file line by line:
    bufferedReader class provides readLine method to be used to read the file line by line.
public static void readFile() throws FileNotFoundException {
FileReader fr = new FileReader(“C:\\Users\\…\\Desktop\\unused.txt”);
BufferedReader br = new BufferedReader(fr);
StringBuffer str = new StringBuffer();
try {
while (br.readLine()!= null){
str.append(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(str);
}
  1. Reverse a string without using reverse function
public static void reverse() {
String str = “I use selenium webdriver. selenium is a tool for web applications.”;
int i = str.length();
StringBuffer strb = new StringBuffer();
for( int j=i-1; j>=0; j–){
strb = strb.append(str.charAt(j));
}
System.out.println(strb);
}
  1. Replace substring with another string in a string
public static void replace() {
String str = “I use selenium webdriver. selenium is a tool for web applications automation.”;
String toBeReplaced = “selenium”;
String toReplacedWith = “Firefox”;
String[] astr = str.split(toBeReplaced);
StringBuffer strb = new StringBuffer();
for ( int i = 0; i <= astr.length – 1; i++ ) {
strb = strb.append( astr[i] );
if (i != astr.length – 1) {
strb = strb.append(toReplacedWith);
}
}
System.out.println(strb);
}

2 comments: