Wednesday, December 10, 2014

Selenium Interview Questions Part - 4



Selenium IDE

Selenium IDE - Interview Questions

1. What do you know about Selenium?
2. What are the technical challenges with selenium?As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.
-->Selenium Supports only web based applications
-->It doesn̢۪t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
-->When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of the test cases
-->Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications
-->There is no object repository concept in Selenium, so maintainability of the objects is very high
-->There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applications
-->Bitmap comparison is not supported by Selenium
-->Any reporting related capabilities, you need to depend on third party tools
-->You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scripting side of selenium
3. What are the test types supported by Selenium?Selenium could be used for testing the web based applications.
The test types can be supported are:1. Functional,
2. Regression,
3. Load testing
The automation tool could be implemented for post release validation with continuous integration tools like:
1. Jenkins,
2. Hudson,
3. Quick Build
4. CruiseCont
4. What are the capabilities of Selenium IDE?Selenium IDE (Integrated Development Environment) works similar to commercial tools like QTP, Silk Test and Test Partner etc. The below mentioned points describes well about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other actions to make a test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. debugging of the test cases with step-by-step can be done
6. Breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can support an extensibility capability allowing the use of add-ons or user extensions that expand the functionality of Selenium IDE
5. What are the challenges with Selenium IDE?Selenium-IDE does not directly support:
1. Condition statements
2. Iteration or looping
3. Logging and reporting of test results
4. Error handling, particularly unexpected errors
5. Database testing
6. Test case grouping
7. Re-execution of failed tests
8. Test case dependency
9. Capture screenshots on test failures
10. Results Report generations
6. Which are the browsers supported by Selenium IDE?Selenium IDE supports only one browser Mozilla Firefox. The versions supported as of now are:
Mozilla Firefox 2.x
Mozilla Firefox 3.x
The versions not supported as of now are:
7. How to execute a single line command from Selenium IDE?Single line command from Selenium IDE can be executed in two ways
1. Right click on the command in Selenium IDE and select "Execute This Command"
2. Select the command in Selenium IDE and press "X" key on the keyboard
8. How to insert a start point in Selenium IDE?Start point Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Set / Clear Start Point"
2. Select the command in Selenium IDE and press "S" key on the keyboard
3. You can have only one start point
4. If you have already set one start point and you selected other command as start point. Then the first start point will be removed and the new start point will be set
9. How to insert a comment in Selenium IDE?Comments in Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Inert New Comment"
2. If you want to comment an existing line. You need to follow the below mentioned steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>
10. How to insert a break point in Selenium IDE?Break point can be set in two ways in Selenium IDE
1. Right click on the command in Selenium IDE and select "Toggle Break Point"
2. Select the command in Selenium IDE and press "B" key on the keyboard
3. If you want to clear the break point once again Spress "B" key on the keyboard
4. You can set multiple break points in Selenium IDE
11. How to debug the tests in Selenium IDE?To debug or execute the test cases line by line. Follow the below mentioned steps
1. Insert a break From the location where you want to execute step by step
2. Run the test case
3. Execution will be paused at the given break point
4. Click on the step (Blue) button to continue with the next statement
5. Click on Run button, to continue executing all the commands at a time
12. How to export the tests from Selenium IDE to Selenium RC in different languages?From selenium IDE the test cases can be exported into the languages
1. .Net
2. Java
3. Perl
4. Python
5. PHP
6. Ruby
The below mentioned steps can explain how to export the test cases
1. Open the test case from Selenium IDE
2. Select File -> Export Test Case As
13. How to export Selenium IDE Test Suite to Selenium RC Suites?From selenium IDE the test suites can be exported into the languages as mentioned below
1. .Net
2. Java
3. Perl
4. Python
5. PHP
6. Ruby
The below mentioned steps can explain how to export the test suites
1. Open the test case from Selenium IDE
2. Select File -> Export Test Suite As
14. Which is the command used for displaying the values of a variable into the output console or log?The command used for displaying the values of a variable into the output console or log - echo
If you want to display a constant string. The below mentioned command can be used
echo <constant string>
ex: echo "The sample message"
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}
Note: Here var1 is the variable
15. Which are the browsers supported by Selenium RC?Supported browsers for Selenium RC include:
1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
16. Which are the Operating Systems supported by Selenium?
Selenium IDE 
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
Selenium Remote Control 
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Selenium Core 
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
17. What is Selenium RC?Selenium-RC is the solution for tests that need a little more than just simple browser actions and a linear execution. Selenium-RC leverages the full power of programming languages, creating tests that can do things like read and write external files, make queries to a database, send emails with test reports, and practically anything else a user can do with a normal application.
You will want to use Selenium-RC whenever your test requires logic not supported by running a script from Selenium-IDE
18. Why Selenium RC is used?Selenium-IDE does not directly support:
1. condition statements
2. iteration
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
The reason behind why Selenium-IDE does not support the above mentioned requirements is IDE supports only HTML language. Using HTML language we cannot achieve the above mentioned requirements. Because HTML does not support conditional, looping and external source connectives.
To overcome the above mentioned problems Selenium RC is used.
Since Selenium RC supports the languages .Net, Java, Perl, Python, PHP, and Ruby. In these languages we can write the programme to achieve the IDE issues
19. Which are the languages supported by Selenium RC?The languages supported by Selenium RC
1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby
20. What is Selenium Grid?Selenium Grid is part of Selenium suite of projects. Selenium Grid transparently distribute your tests on multiple machines so that you can run your tests in parallel, cutting down the time required for running in-browser test suites. This will dramatically speeds up in-browser web testing, giving you quick and accurate feedback you can rely on to improve your web application.
21. What is Selenium WebDriver or Google WebDriver or Selenium 2.0?WebDriver uses a different underlying framework from Selenium̢۪s javascript Selenium-Core. It also provides an alternative API with functionality not supported in Selenium-RC. WebDriver does not depend on a javascript core embedded within the browser, therefore it is able to avoid some long-running Selenium limitations.
WebDriver̢۪s goal is to provide an API that establishes
̢ۢ A well-designed standard programming interface for web-app testing.
̢ۢ Improved consistency between browsers.
̢ۢ Additional functionality addressing testing problems not well-supported in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating WebDriver is another step in that process. The developers of Selenium and of WebDriver felt they could make significant gains for the Open Source test automation community be combining forces and merging their ideas and technologies. Integrating WebDriver into Selenium is the current result of those efforts.
22. What are the capabilities of Selenium WebDriver or Google WebDriver or Selenium 2.0?One should use WebDriver when requiring improved support for
̢ۢ Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1.0.
̢ۢ Handling multiple frames, multiple browser windows, popups, and alerts.
̢ۢ Page navigation.
̢ۢ Drag-and-drop.
̢ۢ AJAX-based UI elements.
23. What is the architecture of Selenium RC?The Selenium Server which launches and kills browsers, and acts as an HTTP proxy for browser requests.
Client libraries for various programming languages, each of which instructs the Selenium Server in how to test the AUT by passing it your test script̢۪s Selenium commands.
The diagram shows the client libraries communicate with the Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript interpreter, executes the Selenium command, which effectively, runs the check you specified in your Selenese test script.
24. What is the architecture of Selenium Grid?
The below mentioned theory explains about the setup of Selenium Grid with architecture and how it works.Selenium Grid builds on the traditional Selenium setup, taking advantage of the following properties:
* The Selenium test, the application under test, and the remote control/browser pair do not have to be co-located. They communicate through HTTP, so they can all live on different machines.
* The Selenium tests and the web application under test are obviously specific to a particular project. Nevertheless, neither the Selenium remote control nor the browser is tied to a specific application. As a matter of fact, they provide a capacity that can easily be shared by multiple applications and multiple projects.
Consequently, if only we could build a distributed grid of Selenium Remote Controls, we could easily share it across builds, applications, projects - even potentially across organizations. Of course we would also need to address the scalability issues as described earlier when covering the traditional Selenium setup. This is why we need a component in charge of:
* Allocating a Selenium Remote Control to a specific test (transparently)
* Limiting the number of concurrent test runs on each Remote Control
* Shielding the tests from the actual grid infrastructure
Selenium Grid calls this component the Selenium Hub.
* The Hub exposes an external interface that is exactly the same as the one of a traditional Remote Control. This means that a test suite can transparently target a regular Remote Control or a Selenium Hub with no code change. It just needs to target a different IP address. This is important as it shields the tests from the grid infrastructure (which you can scale transparently). This also makes the developer’s life easier. The same test can be run locally on a developer machine, or run on a heavy duty distributed grid as part of a build – without ever changing a line of code.
* The Hub allocates Selenium Remote Controls to each test. The Hub is also in charge of routing the Selenese requests from the tests to the appropriate Remote Control as well as keeping track of testing sessions.
* When a new test starts, the Hub puts its first request on hold if there is no available Remote Control in the grid providing the appropriate capabilities. As soon as a suitable Remote Control becomes available, the Hub will serve the request. For the whole time, the tests do not have to be aware of what is happening within the grid; it is just waiting for an HTTP response to come back.
25. Does Selenium support mobile internet testing?Selenium supports Opera. And opera is used in most of the Smart phones. So whichever Smart phone supports opera, selenium can be used to test. So, one can use Selenium RC to run the tests on mobiles.
26. Does Selenium support Google Android Operating System?Yes, Selenium Web Driver or Google Web Driver or Selenium 2.0 supports Android Operating System. There are several libraries written to support Android Operating System.
27. What are the types of text patterns available in Selenium?There are three types of patterns available in Selenium
1. globbing
2. regular expressions
3. exact
28. How to use regular expressions in Selenium?Regular expressions in Selenium IDE can be used with the keyword - regexp: as a prefix to the value and patterns needs to be included for the expected values.
For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
in the above example Flight Confirmation is continuously changing each time you run the test case. So this can be written with a regular expression as mentioned below
Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}
29. What are the regular expression patterns available in Selenium?Selenium regular expression patterns offer the same wide array of special characters that exist in JavaScript. Below are a subset of those special characters
PATTERN
MATCH
.
any single character
[ ]
character class: any single character that appears inside the brackets
*
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)
|
alternation: the character/group on the left or the character/group on the right
( )
grouping: often used with alternation and/or quantifier

30. What is Selenese?Selenium set of commands which are used for running the test are called asSelenese.
There are three types of Selenese, those are:
1. Actions - used for performing the operations and interactions with the target elements
2. Assertions - used as check points
3. Accessors - used for storing the values in a variable
31. How do you add check points or verification points in Selenium?check points or verification points are known as Assertions in Selenium. The keywords with below mentioned prefix will be used for adding check points or verification points.
1. verify
2. assert
3. waitFor
32. What is Assertion in Selenium?Assertion is nothing but a check or verification point.
Assertion verifies the state of the application conforms to what is expected.
Examples include â€Å“make sure the page title is X” and â€Å“verify that this checkbox is checked.
33. What are the types of Assertions there in Selenium?Selenium Assertions can be used in 3 modes:
1) assert - When an assert fails, the test will be aborted. If you are executing test suite, the next state case will start
2) verify - When a verify fails, the test will continue execution, logging the failure.
3) waitFor - waitFor commands wait for some condition to become true (which can be useful for testing Ajax applications). They will succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the current timeout setting
34. When to use Assert, Verify and WaitFor in Selenium?1) assert - If the expected value is mandatory to continue with the next set of steps we will use Assert. As Assert aborts the test, if the expected value doesn't match. It is good to use for any mandatory checks.
2) verify - If the expected value is optional to continue with the next set of steps we will use Verify. As Verify continues executing with the next set of steps, if the expected value doesn't match. It is good to use for any optional checks.
3) waitFor - If your test needs to wait, if the expected value is not matching we use waitFor. We normally use waitFor for AJAX kind of controls loading within a page
35. What is an Accessor in Selenium?Accessor is one of the type of Selenese.
I. Accessors are used for storing the value of a target in a variable.
Ex:
1) storeTitle - Stores the title of a window in a variable
2) storeText - Stores the target element text in a variable
II. Accessors are also used for evaluating the result and storing the result in a variable
Ex: storeTextPresent - Evaluates whether the text is present in the current window. If the text is present stores true in the variable else stores false
Ex: storeEementPresent - Evaluates whether the element is present in the current window. If the element is present stores true in the variable else stores false
36. When to use Accessors in Selenium?Accessors are mostly used for storing the value in a variable.
The variable can be used for following reasons:
1) To get the value from an element and comparing with some dynamic value
2) To take a logical decision to execute the test steps
ex: if the value of the variable true execute step1 and step2 else step3 and step4
3) To execute some statements in a loop based on the value returned by the element
37. How to capture bitmaps in Selenium?Bitmaps are captured using the Selenium set of commands. There are two modes of capturing the bitmaps
1) Capture the bitmap for the entire page - it captures the browser main page area of AUT
2) Capture the bitmap for the screen shots - it captures the entire screen shot like the print scree that you give from your keyboard
Selenium doesn't support bitmap capturing for an element on AUT.
38. Which are the commands used for capturing the bitmaps?
captureEntirePageScreenshot
captureEntirePageScreenshotAndWait
Note:
39. What is the difference between captureEntirePageScreenshot and CaptureScreenShot?captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox
3. Accepts two arguments. one is the file name to be saved and other argument is back ground color
CaptureScreenShot
1. This captures the System screen shot
2. This supports all the browsers when you run from Selenium RC
3. Accepts one argument. That is the file name to be saved.
40. How do you set user extensions in Selenium IDE?1. Open user-extensions.js with an editor (Notepad, etc.); it's found in the selenium\core\scripts folder. If it doesn't exist, just create it.
2. If you need to, commit the user-extensions.js file (like if you use subversion).
3. Open Selenium IDE and choose the Options menu and then Options... from that menu.
4. Make sure the path to your user-extensions.js file is entered in the Selenium Core extensions field (like \selenium\core\scripts\user-extensions.js)
5. Press OK button on options
6. Restart the IDE to reflect your extensions.
Note: 
41. What are the limitations of Selenium IDEThe limitations of Selenium IDE are:
1) Selenium IDE uses only HTML language
2) Conditional or branching statements execution like using of if, select statements is not possible
3) Looping statements using is not possible directly in Selenium HTML language in ide
4) Reading from external files like .txt, .xls is not possible
5) Reading from the external databases is not possible with ide
6) Exceptional handling is not there
7) A neat formatted Reporting is not possible with ide
To eliminate the above issues we use Selenium RCAfter reopen, Selenium IDE may show compilations errors if the user-extensions.js file has any syntax errors. This command runs with only mozilla firefox when you run the tests from RC. Other browsers it will not support
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshotAndWait for details.
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshot for more details
Used for running tests
Operating Systems Supported:
Used for starting browser and run tests
Operating Systems Supported:
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
earlier versions of Mozilla Firefox 2.x
Mozilla Firefox 4.x

Selenium is a suite of tools for web automation testing. Selenium first came to life in 2004 when Jason Huggins was testing an internal application at Thought Works. Selenium was a tremendous tool, it wasn’t without its drawbacks. Because of its JavaScript based automation engine and the security limitations browsers apply to JavaScript, different things became impossible to do. 
Selenium Suite of projects includes:
Selenium IDE
Selenium Core
Selenium 1 (known as Selenium RC or Remote Control)
Selenium 2 (known as Selenium Web driver)
Selenium-Grid

Selenium RC

Selenium RC - Interview Questions

Selenium RC Interview Questions
1. What are the pre-requisites to run Selenium RC tests with Junit?
The pre-requisites to run Selenium RC tests with Junit:
1) Jre 1.5 or better version needs to be installed
2) /jre/bin folder must be added in environment variable "path"
3) Junit folder path must be added to path or build path in eclipse
4) Selenium Java Client drivers needs to be added to the path for execution
2. How to configure Selenium RC with eclipse to run Junit Tests?1) Download eclipse. 
click here to download the software
2) Open eclipse -> Workspace Launcher window will open
3) Create a workspace by giving meaningful name
3) Click on Workbench
4) Create a project of type java
5) Create a package under src folder of the package
6) Add Junit to the build path
7) Add selenium rc java client driver to the build path
8) Now drag and drop your test script (.which is exported from Selenium IDE) to the package created
3. Which is the command used for running the Selenium RC Server?The procedure followed to run the Selenium RC Server is:
1. Open the command prompt.
2. Change the folder path to Selenium RC Server
3. Issue the command "java -jar selenium-server.jar"
4. For more options on how to start selenium server. Please have a look at
4. How do you run selenium commands in slow motion in Selenium RC?You can run the selenium commands in RC slow motion by two ways:
selenium.setSpeed
thread.sleep
5. What is the difference between Thread.Sleep() and Selenium.setSpeed()?
selenium.setSpeed
thread.sleep
6. Why do you use assert and verify statements in Selenium RC without referring to selenium?SeleneseTestCase is the class which is having
1. assertTrue
2. verifyTrue
3. assertEquals
4. verifyEquals
We use SeleneseTestCase class to extend the selenium test class file.
For Ex: the test class is declared as follows
public class BookFlightSel1 extends SeleneseTestCase
In the above example SeleneseTestCase is the base class and BookFlightSel1 is the derived class. So, we can directly call and use the parent class methods verify and assert without instantiating the class in BookFlightSel1 class.
7. Which are the annotations generated with JUnit 4 tests in Selenium IDE?The annotations generated with JUnit 4 tests in Selenium are:
1. @Before public void method() - Will perform the method() before each test. This method can prepare the test
2. @Test public void method() - Annotation @Test identifies that this method is a test method.environment, e.g. read input data, initialize the class)
3. @After public void method() - Test method must start with test@Before - this annotation is used for executing a method before
8. What are the challenges with Selenium RC test suites when running in JUnit?The challenges with Selenium RC test suites when running in JUnit
1. Each test case of Selenium RC test will invoke the browser and closes after playing back
2. All the Test cases cannot run on a single browser session
3. If there is any dependency between the test cases, it is very difficult to execute
4. Running the test suites in junit will be helpful for only independent test cases.
Note: The dependent test case related issues can be addressed by using TestNG with junit
9. What are the advantages of using TestNG over Junit?The advantages of using TestNG over Junit:
1. The challenges of junit can be addressed using TestNG read 
What are the challenges with Selenium RC test suites when running in JUnit? for more details
2. You can execute the test cases dependent with each other read 
Runnning Selenium RC Tests Sequentially using TestNG for more details
3. You can execute test cases in a group read 
Use Group in TestNG framework for more details
4. You can generate the reports using TestNg
10. What are the basic annotations used to run TestNG tests in Selenium?The basic annotations used to run TestNG tests in Selenium RC:
1. @BeforeClass: The annotated method with @BeforeClass will be run before the first test method in the current class is invoked.
2. @AfterClass: The annotated method with @AfterClass will be run after all the test methods in the current class have been run.
3. @BeforeMethod: The annotated method with @BeforeMethod will be run before each test method.
4. @AfterMethod: The annotated method with @AfterMethod will be run after each test method.
5. @Test: Marks a class or a method @Test with as part of the test.
11. How to run test cases with dependent in Selenium using TestNG?The @Test should be followed by (dependsOnMethods = "testLogin")
Note:- The test case will be executed after the testLogin case
Ex: @Test(dependsOnMethods = "testLogin")
12. How to run the test cases in group in Selenium using TestNG?Test cases in group in Selenium using TestNG will be executed with the below options.
If you want to execute the test cases based on one of the group like regressiontest or smoketest
@Test(groups = {"regressiontest", "smoketest"})
13. How to execute the test cases in an XML format using TestNG in Selenium?If you want to execute a java file MercTestNgSuite.java which is there in the package com.src.testng. You can use the below mentioned code in a xml file. And the test can be run by right clicking the XML and running as TestNG Suite
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" skipfailedinvocationCounts="false" verbose="1" name="MercPrj" junit="false" parallel="false" annotations="JDK">
<test verbose="2" name="com.src.testng.MercTestNgSuite" junit="false" annotations="JDK">
<classes>
<class name="com.src.testng.MercTestNgSuite"/>
</classes>
</test>
</suite> ??
14. How to incude or exclude the selenium rc test cases using xml in TestNG?Including or excluding of selenium rc test cases using xml in TestNG can be done using the keywords include or exlude
For including a test case we need to use <include name="method name"/> under the class whichever the method you want to include
For excluding a test case we need to use <exclude name="method name"/> under the class whichever the method you want to include
For example if you have a class MercTestNgSuite in package com.src.testng want to include the methods like:
1. testLogin1
2. testFindFlights
3. testSelectFlights
4. testFillUserDetails
5. testVerifyFlightConf
and exclude
6. testLogout
the xml can be written as mentioned below.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" skipfailedinvocationCounts="false" verbose="1" name="MercPrj" junit="false" parallel="false" annotations="JDK">
<test verbose="2" name="com.src.testng.MercTestNgSuite" junit="false" annotations="JDK">
<classes>
<class name="com.src.testng.MercTestNgSuite"/>
<methods>
<include name="testLogin1"/>
<include name="testFindFlights"/>
<include name="testSelectFlights"/>
<include name="testFillUserDetails"/>
<include name="testVerifyFlightConf"/>
<exclude name="testLogout"/>
</methods>
</classes>
</test>
15. How to execute the selenium test suite with testNG in XML?Assume that you have two classes which are having suite of test cases with the below mentioned methods.
class1 or suite 1:
class1 or suite 2:
The two class suites can be executed as mentioned
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" skipfailedinvocationCounts="false" verbose="1" name="MercPrj" junit="false" parallel="false" annotations="JDK">
<test verbose="2" name="com.src.testng.*" junit="false" annotations="JDK">
<classes>
<class name="com.src.testng.MercTestNgSuite"/>
<methods>
<include name="testLogin1"/>
<include name="testFindFlights"/>
<include name="testSelectFlights"/>
<include name="testFillUserDetails"/>
</methods>
<class name="com.src.testng.MercTestNgSuite2"/>
<methods>
<include name="testLogin1"/>
<include name="testFindFlights"/>
<include name="testSelectFlights"/>
<include name="testFillUserDetails"/>
<include name="testVerifyFlightConf"/>
<include name="testLogout"/>
</methods>
</classes>
</test>
</suite>
16. How to run Selenium IDE test suite with user extensions using Selenium Remote Control?to run Selenium IDE test suite with user extensions using Selenium Remote Control we need to use the below command.
java -jar selenium-server.jar -userExtensions user-extensions.js -htmlSuite "*<browser>" "<base URL>" "<Selenium test suite file>" "<results log file>" -timeout <millise>
17. How to start selenium rc server with user extensions?The command used is
java -jar selenium-server.jar -userExtensions user-extensions.js
Note: In this case, the java script file user-extensions.js file name should always fixed. If the name or extension is changed the selenium rc server will not start.
18. What are the limitations of selenium RCThe limitations of selenium RC are:
1) Switching between the multiple instances of the same browser is not possible
2) Switching between the multiple instances of the different browsers is not possible
3) Browser navigation, like back and forward button emulations is not possible
4) Limited features in terms of drag and drop of objects
5) To work with Ajax based UI elements there are very limited features are there with Selenium RC
To overcome the above limitations we use selenium web driver or google web driver
19. How to do database testing using selenium rc?There are no selenium specific commands to do the database testing. But, you have the work around with native language. Here is the example how you can make database testing in selenium. The below mentioned commands will help you to begin with.
Before you use the below code You should have created the DSN name for MS SQL Server DB or Oracle DB using ODBC drivers. Here the name that we have used for the database DSN name is QT_Flight32. And the table in that database we are using is Orders. Hope the remaining steps you can easily understand.
//KEEP THE NAME OF THE PACKAGE
//IMPORT THE SQL PACKAGE
//DECLARE THE CLASS
//WRITE THE MAIN METHOD TO CONNECT TO THE DATABASE 
try{
// LOAD THE DATABASE DRIVER
// ESTABLISH THE CONNECTION TO THE DATABASE
// GET A STATEMENT FOR THE CONNECTION
// PREPARE THE SQL STATEMENT
// EXECUTE THE SQL QUERY AND STORE IN RESULTS SET
// LOOP THE RESULT TILL IT REACHED END
// CLOSE THE RESULT, STATEMENT AND CONNECTION
}
// HANDLE THE SQL EXCEPTION
catch( SQLException se ) {
System.out.println( "SQL Exception:" ) ;
// PRINT TILL ALL THE ECEPTIONS ARE RAISED
System.out.println( "State : " + se.getSQLState() ) ;
System.out.println( "Message: " + se.getMessage() ) ;
System.out.println( "Error : " + se.getErrorCode() ) ;
se = se.getNextException() ;
}
}
//CATCH THE CLASS EXCEPTION
catch( Exception e ) {
System.out.println( e ) ;
}
}
}
while( se != null ) {
rs.close() ;
stmt.close() ;
conn.close() ;
// rs.getString(1) - FIRST COLUMN
// rs.getString(2) - SECOND COLUMN ETC
while( rs.next() )
System.out.println( rs.getString(1) + rs.getString(2)+ rs.getString(3)+ rs.getString(4)) ;
ResultSet rs = stmt.executeQuery( strSQL ) ;
String strSQL = "SELECT * FROM Orders";
Statement stmt = conn.createStatement() ;
Connection conn = DriverManager.getConnection( "jdbc:odbc:QT_Flight32" ) ;
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
public static void main( String args[] )
{
class JDBCODBCTestCase
{
import java.sql.* ;
package com.src.test;the class by name MercTestNgSuite2 in the package com.src.testng with the methods
1. testLogin1
2. testFindFlights
3. testSelectFlights
4. testFillUserDetails
5. testVerifyFlightConf
6. testLogout the class by name MercTestNgSuite in the package com.src.testng with the methods
1. testLogin1
2. testFindFlights
3. testSelectFlights
4. testFillUserDetails
1. takes a single argument in integer format
ex: thread.sleep(2000) - will wait for 2 seconds
2. Waits for only once at the command given at sleep.

1. takes a single argument in string format
ex: selenium.setSpeed("2000") - will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in setSpeed.
1: What is Selenium 2.0? I have heard this buzz word many times.

Answer: Selenium 2.0 is a consolidation of two web testing tools:
a) Selenium RC and
b) Web Driver,
It claims to give best of both words: Selenium and Web Driver.
2: Why are two tools being combined as Selenium 2.0?
Answer: Selenium 2.0 promises to give much cleaner API than Selenium RC and at the same time not being restricted by JavaScript Security restriction like same origin policy.
3: 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
4: So how do I specify my browser configurations with Selenium 2.0?
Answer: Selenium 2.0 offers following browser/mobile configuration:
a) Android Driver,
b) Chrome Driver,
c) EventFiringWebDriver,
d) Firefox Driver,
e) HtmlUnitDriver,
f) InternetExplorerDriver,
g) IPhoneDriver,
h) IPhoneSimulatorDriver,
i) 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 classes.
5: How is Selenium 2.0 configuration different from 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. 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 Web Driver.
6. Selenium Benefits over Web Driver.
Selenium supports many browsers and many languages, Web Driver needs native implementations for each new language/browser combo.
Very mature and complete API
Currently (Sept 2010) supports JavaScript alerts and confirms better
Benefits of Web Driver Compared to Selenium
• Native automation faster and a little less prone to error and browser configuration
• Does not Requires Selenium-RC Server to be running
• Access to headlessHTMLUnit can allow really fast tests
• Great API
7. What is Web Driver?
Web Driver uses a different underlying framework from Selenium’s javascript Selenium-Core. It also provides an alternative API with functionality not supported in Selenium-RC. WebDriver does not depend on a JavaScript core embedded within the browser; therefore it is able to avoid some long-running Selenium limitations.
WebDriver’s goal is to provide an API that establishes
A well-designed standard programming interface for web-app testing.
• Improved consistency between browsers.
• Additional functionality addressing testing problems not well-supported in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating WebDriver is another step in that process. The developers of Selenium and of WebDriver felt they could make significant gains for the Open Source test automation community be combining forces and merging their ideas and technologies. Integrating WebDriver into Selenium is the current result of those efforts.
8.When to Use WebDriver?
One should use WebDriver when requiring improved support for
* Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1.0.
* Handling multiple frames, multiple browser windows, popups, and alerts.
* Page navigation.
* Drag-and-drop.
* AJAX-based UI elements.
Advantages of web driver compared to selenium.
1) Support for iPhone and Android testing
2) Implementation of listeners - a much awaited feature
3) Better features for Ajax testing.
4) You can easily simulate clicking on front and back button of browser.
5) You can extract objects in bulk like QTP. For ex - extract all links of page. With RC this was a big hastle
6) Unlike RC you don’t have to start a server in webdriver.
7) You can simulate movement of a mouse using selenium.
8) Tabs and pops are more or less the same. RC can also handle and Webdriver can also handle.
9) You can find coordinates of any object using Webdriver.
10) You have classes in Webdriver which help you to simulate key press events of keyboard.
10) Keyword driven framework is very easy to build in webdriver.
9.Which browsers does WebDriver support?
The existing drivers are the ChromeDriver, InternetExplorerDriver, FirefoxDriver, OperaDriver and HtmlUnitDriver. For more information about each of these, including their relative strengths and weaknesses, please follow the links to the relevant pages. There is also support for mobile testing via the AndroidDriver and IPhoneDriver.

Selenium FAQS asked in Interviews

1. What is data driven framework?
This frame work is used when an application is test with multiple sets of data. The data is passed to the scripts from data files like excel files, csv files, ODBC (Open Database Connectivity) and ADO (ActiveX Data Objects) objects.
Data driven framework is a systematic approach to test an application. It may contain all the structured information like data driven files, library functions, and user defined functions. Using the driver script, we can import theses files as a input to the application and test it. This is called data driven frame work. Data driven approach is being by most of the industries
2 what is keyword, hybrid framework?
Frame Work is the model or structure we follow for a Project. It is the approach that we follow to automate the Project. There are so many types of framework in QTP.
1. Data driven frame work
2. Keyword driven frame work
3. Module driven framework
4. Hybrid driven frame work
The framework you choose depends on the model of your Project. Usually most of projects fall under hybrid driven frame work.
Data driven framework:
Keyword driven framework:
Module driven frame work:
Hybrid Frame work:
This will be the combination of the any frameworks like Keyword driven+DataDriven or Data driven + modular driven. we will divide entire project in to modules and write functions or procedures for each and every module and automate the project. Hybrid driven framework: it is combination of Data driven and module driven framework.Firstly we should add the objects to repository ( Shared repository is preferable) Then we can generate/write scripts for each functionality and save them as the library files ( .vbs files)Then we have to associate all these library files(which are generated to test different functionalities) to Quick Test. Here we divide the entire project in to modules and start automation by writing data driven scripting for each one of them. We will have test data either in excel sheet or flat files or from database...we will pass that test data in to the script and perform data driven testing.
3 what is iframe?
An <iframe></iframe> element allows the placement of an inline frame within an HTML document, which allows the display of another, separate document. Any content between the start and close tag of the <iframe> element is ignored.
There are various ways of selecting an IFrame with selenium and accessing data within the IFrame: By Name:selenium.selectFrame("mainFrame"); //name of the IFrame
By DOM:
Remember index starts at 0, so "index=1″ will select the second IFrame. We can call the selectFrame() function multiple times to select the nested IFrames:
selenium.selectFrame("index=1″);
selenium.selectFrame("index=1″); will select the second IFrame within the second IFrame from the root
4 what is difference b/w xpather and xpath checker?
Firebug - the right-click "copy XPath" command copies the path as all lower-case, and some XML parsers (like the MXSML parser used in Final Builder) are case-sensitive - so you'll need to correct the casing of your Firebug-copied XPath statement otherwise your parser won't find any matching nodes.
XPather
...generates
The XPather is a simple
selenium.selectFrame("dom=window.frames[1]"); //second IFrame By Index: selenium.selectFrame("index=1″); //second IFrameXPaths while browsing or inspecting HTML/XML/*ML documents; evaluates your XPaths and inspects the results; extracts the content.Firefox extension that integrates both with the browser and its DOMInspector. Thus, is't very lightweight and cross-platform. It is valuable mainly as a web/XML-app development and hacking tool.XPath Checker XPather
String-match Patterns
Feature rich XPath generator, editor, inspector and simple extraction tool...
 
5 what is diff b/w Firefox and chrome and ie?
à Selenium scripts will run very fast in Firefox when we compare with the IE.
6 .how can u capture the entire pages, one page in single window? How it use I mean that cmd?
captureEntirePageScreenshot ( filename,kwargs )
·         filename - the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by native code.

·         kwargs - a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" . Currently valid options:
background
the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text).
 
7. How many types of pattern matching, list of it? Like regular expressions, group exp,exact expressions?
Various Pattern syntaxes are available for matching string values:
glob:
Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a kind of limited regular-expression syntax typically used in command-line shells. In a glob pattern, "*" represents any sequence of characters, and "?" represents any single character. Glob patterns match against the entire string.
regexp:
Match a string using a regular-expression. The full power of JavaScript regular-expressions is available.
exact:
Match a string exactly, verbatim, without any of that fancy wildcard stuff.
If no pattern prefix is specified, Selenium assumes that it's a "glob" pattern.
8 what is diff b/w wait for page to load, thread. Sleep, set speed?
Sleep, suspends the current thread for a period of time.
The expiration of that time is what will make the thread runnable.

Wait, suspends the current thread until some event has done.
9 what are the different startup modes in selenium RC
à Mainly we had 2 types to startup modes in selenium RC.
you can launch Selenium Remote Control server using following command ( Make sure that you are into directory where selenium-server.jar is located or this directory is in your path variable ) -
java -jar selenium-server.jar
This command should start Selenium Server on your machine and your automation scripts are ready to interact with your web application using this server. You can leave this server up and running while you are developing and executing your automation scripts. If you wish, you can also start Selenium Remote Control in interactive mode and start playing with its various commands on command prompt itself. In order to do that, you need to supply a command line option called interactive.
java -jar selenium-server.jar -interactive
Apart from this there are many command line options that you can specify while starting selenium RC.
-port :
-timeout : an integer number of seconds before we should give up
-interactive:
-singleWindow:
-profilesLocation:
-forcedBrowserMode : sets the browser mode to a single argument (e.g. "*iexplore") for all sessions, no matter what is passed to getNewBrowserSession
-forcedBrowserModeRestOfLine :
-userExtensions :
-browserSessionReuse:
-firefoxProfileTemplate <dir>:
-debug: puts you into debug mode, with more trace information and diagnostics on the console
-browserSideLog:
-ensureCleanSession:
-trustAllSSLCertificates:
-log :
-htmlSuite :
-proxyInjectionMode:
-dontInjectRegex :
-userJsInjection :
-userContentTransformation :
10 how to automate flash based application?
Both selenium RC and selenium Webdriver can be used for flash/flex application testing. Procedure is same for testing flash and flex applications using selenium. FlashSelenium API in Selenium RC helps us to test flash/flex based applications using RC. While in webdriver, you need to make your own custom Javascript Execution functions in order to test flash applications using Selenium. But in order to test such appications, you need to make sure that you have the access to source code of the application. This means that you cannot just go and test any flash application present on the internet.
To test flash application u need to add below flash jar file to the eclipse.
"Flashselenium-java-client-extension.jar"
à While writing the code u need to import the flash lib
import com.thoughtworks.selenium.FlashSelenium;

a regular expression which is matched against all test HTML content; the second is a string which will replace matches. These flags can be used any number of times. A example of how this could be useful: if you add "-userContentTransformation https http" then all "https" strings in the HTML of the test application will be changed to be "http". specifies a JavaScript file which will then be injected into all pagesan optional regular expression that proxy injection mode can use to know when to bypss injection puts you into proxy injection mode, a mode where the selenium server acts as a proxy server for all content going to the test application. Under this mode, multiple domains can be visited, and the following additional flags are supported: Run a single HTML Selenese (Selenium Core) suite and then exit immediately, using the specified browser (e.g. "*firefox") on the specified URL (e.g. http://www.google.com"). You need to specify the absolute path to the HTML test suite as well as the path to the HTML results file we'll generate. writes lots of debug information out to a log file Forces the Selenium proxy to trust all SSL certificates. This doesn't work in browsers that don't use the Selenium proxy. If the browser does not have user profiles, make sure every new session has no artifacts from previous sessions. For example, enabling this option will cause all user cookies to be archived before launching IE, and restored after IE is closed. enables logging on the browser side; logging messages will be transmitted to the server. This can affect performance. normally, we generate a fresh empty Firefox profile every time we launch. You can specify a directory to make us copy your profile directory instead. stops re-initialization and spawning of the browser between tests
-avoidProxy: By default, we proxy every browser request; set this flag to make the browser use our proxy only for URLs containing '/selenium-server' indicates a JavaScript file that will be loaded into selenium sets the browser mode to all the remaining tokens on the line (e.g. "*custom /some/random/place/iexplore.exe") for all sessions, no matter what is passed to getNewBrowserSession Specifies the directory that holds the profiles that java clients can use to start up selenium. Currently supported for Firefox only. puts you into a mode where the test web site executes in a frame. This mode should only be selected if the application under test does not use frames.puts you into interactive mode. See the tutorial for more details the port number the selenium server should use (default 4444) 
stringregexp pattern
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see http://www.screengrab.org and http://snapsie.sourceforge.net/ for details.
Arguments:
An interactive editor for XPath expressions

Data Driven Testing using Selenium RC with JUnit

How to do Data Driven Testing using Selenium RC with JUnit
There are many ways to do Data driven tests.I used Excel sheet for reading data and FileInputStream method.
Below script explains you how to Read data from excel sheet and use the data to search google.
I am using Eclipse, selenium RC, Junit and Excel sheet for this script.

--->Create a Java project in eclipse.
--->Create a new class DatadrivenJUnit.
--->Paste the below code in Eclipse.
--->Chnage the path of excel file according to your requirement.
Please note that selenium will support only .xls format plese do not forget to change the excel file to .xls if you are using MS-office2007.
Below is the code
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;

public class DatadrivenJUnit extends SeleneseTestCase
{
public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception 
{
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testDatadrivenJUnit() throws Exception
{
FileInputStream fi=new FileInputStream("F:\\Framework\\testdata\\search.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
selenium.open("
http://www.google.com/");
selenium.windowMaximize();
for (int i = 1; i < s.getRows(); i++)
 { //Read data from excel sheet
 selenium.type("name=q",s.getCell(0,i).getContents());
 selenium.click("btnG");
 Thread.sleep(1000); } }
@AfterClass
 public void tearDown() throws InterruptedException{
selenium.stop();
 seleniumserver.stop();
}
 }

Data Driven Testing Using Selenium RC with TestNG

How to do Data Driven Testing using TestNG 
There are many ways to do Data driven tests.I used Excel sheet for reading data and FileInputStream method.
Below script explains you how to Read data from excel sheet and use the data to search google.
I am using Eclipse, selenium RC, TestNG and Excel sheet for this script.

--->Create a Java project in eclipse
--->Create a package name as test
--->Create a new class DatadriventestNG.
--->Paste the below code in Eclipse.
--->Chnage the path of excel file according to your requirement.
Please note that selenium will support only .xls format plese do not forget to change the excel file to .xls if you are using MS-office2007.
Below is the code

package test;
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
public class DefaultTNG {
public Selenium selenium;
public SeleniumServer seleniumserver;
  @BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://");
seleniumserver.start();
selenium.start();
}

@Test
public void testDefaultTNG()throws Exception {

  FileInputStream fi=new FileInputStream("F:\\Framework\\testdata\\search.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
selenium.open("
http://www.google.com/");
selenium.windowMaximize();
for (int i = 1; i < s.getRows(); i++)
 { 
//Read data from excel sheet
 selenium.type("name=q",s.getCell(0,i).getContents());
 selenium.click("btnG");
 Thread.sleep(1000); } 
}
@AfterClass
 public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
   
 }
 }

Login Scenario - Providing Login Detail from Excel Sheet

Excel Sheet format should be in .XLS format
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRagQu7NRn8MqrHlbxSPukL13pvoGNYxEut1UkLSwhDdRP1PIcnZUV4RexuhVgQD6_WTtgx9bR9I3u2MbB84OIGK7aNNWS2V3BUhjxfvxZG1KdnlQTRHZXT-cYL3EefTYe8Gm58SE6Hkc/s320/LoginScenario.png
import java.io.FileInputStream;

import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;

public class Loginexcel {
public Selenium selenium;
public SeleniumServer seleniumserver;

@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}

@Test
public void testDefaultTNG()throws Exception {
FileInputStream fi=new FileInputStream("E:\\Selenium\\LoginExcel.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
selenium.open("http://127.0.0.1/orangehrm-2.6/login.php");
selenium.windowMaximize();
for (int i = 1; i < s.getRows(); i++)
{ 
//Read data from excel sheet
String s1 = s.getCell(0,i).getContents();
String s2 = s.getCell(1,i).getContents();
selenium.type("txtUserName",s1);
selenium.type("txtPassword",s2);
selenium.click("Submit");
Thread.sleep(2000); 
selenium.click("Link=Logout");
} 
}
@AfterClass
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
}

Write results to excel sheet

Write results to excel sheet 


After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel sheet....
Below is the sample script to write results to excel sheet...
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;

public class Importexport1 {
public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testImportexport1() throws Exception {
// Read data from excel sheet
FileInputStream fi = new FileInputStream(
"F:\\Framework\\testdata\\Login1_Credentials.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
String a[][] = new String[s.getRows()][s.getColumns()];
// Write the input data into another excel file
FileOutputStream fo = new FileOutputStream(
"F:\\Framework\\Results\\LoginResult1.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("loginresult1", 0);
selenium.open("http://www.gmail.com");
selenium.windowMaximize();
System.out.println("s.getRows() = " + s.getRows());
for (int i = 0; i < s.getRows(); i++) {
System.out.println("s.getColumns = " + s.getColumns());
for (int j = 0; j < s.getColumns(); j++) {
a[i][j] = s.getCell(j, i).getContents();
Label l = new Label(j, i, a[i][j]);
Label l1 = new Label(2, 0, "Result");
ws.addCell(l);
ws.addCell(l1);
}
}
for (int i = 1; i < s.getRows(); i++) {
selenium.type("Email", s.getCell(0, i).getContents());
selenium.type("Passwd", s.getCell(1, i).getContents());
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");
System.out.println("the value of aa is::" + aa);
if (aa)
{
Label l3 = new Label(2, i, "fail");
ws.addCell(l3);
System.out.println("Login Failure");
Thread.sleep(10000);
} else {
Label l2 = new Label(2, i, "pass");
ws.addCell(l2);
selenium.click("link=Sign out");
Thread.sleep(10000);
} 
}
wwb.write();
wwb.close();
}
@AfterClass
public void tearDown() throws Exception {
selenium.stop();
seleniumserver.stop();
}
}
Your input data should be like this....

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyPN7RW3fj9bjFWWORqB6FzpK7RZkZ-zsmiAc_IVvz99zFQgT3-WrOgK9j8aFVwThJEgBezlTpH0riEIwPnDe58NFb82oplvpOUEpFIXiCWPDluyC7enVIRhZCr1Q9-wMiVmKMsfCOWKg/s320/Login1_Credentials.png

Database Connection Using Selenium

Database Connection Using Selenium 

MS Access with Java through JDBC-ODBC connection
Microsoft has provided a method to build a quick Jet-Engine database on your computer without the need for any specific database software (it comes standard with Windows). Using this method, we can even create a blank Microsoft Access database without having MS Access installed!
MS Access data bases can be connected to via ODBC. Instead of accessing the database directly, we can access it via a Data Source Name (DSN). Here's how to set up a DSN on your system:
Open Windows' ODBC Data Source Administrator as follows: 
In Windows 95, 98, or NT, choose Start > Settings > Control Panel, then double-click the ODBC Data Sources icon. Depending on your system, the icon could also be called ODBC or 32bit ODBC. 
In Windows 2000, choose Start > Settings > Control Panel > Administrative Tools > Data Sources. 
In the ODBC Data Source Administrator dialog box, click the System DSN tab. 
Click Add to add a new DSN to the list. 
Scroll down and select the Microsoft Access (.MDB) driver 
Type in the name "TestDB" (no quotes, but leave the cases the same) for the Data Source Name 
Click CREATE and select a file to save the database to (I chose "d:\java\TestDB.mdb") - this creates a new blank MS Access database! 
Click "ok" all the way out Now our data source is done! 
Here's a complete program showing how to access your new DSN data source:
package qtt.selenium;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import com.thoughtworks.*;
import com.thoughtworks.selenium.DefaultSelenium;
import org.junit.*;
import org.openqa.selenium.server.SeleniumServer;
public class DBtest
{
DefaultSelenium selenium;
SeleniumServer server;
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:TestDB";
String username = "";
String password = "";
@Before
public void setup()throws Exception
{
server = new SeleniumServer();
server.start();
selenium = new DefaultSelenium("127.0.0.1",4444,"*chrome","http://");
selenium.start();
}
@Test
public void test()throws Exception
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
Statement st = conn.createStatement();
// st.executeUpdate("drop table survey;");
st.executeUpdate("create table suresh(id int,name varchar(30),Homesite varchar(30));");
st.executeUpdate("insert into suresh (id,name,Homesite) values (1,'SURESH','selenium-suresh.blogspot.com')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM suresh");
if(rs.next());
{
String homesite = rs.getString(3);
selenium.open(homesite);
selenium.windowMaximize();
Thread.sleep(30000);
}
}
@After
public void teardown() throws Exception
{
selenium.stop();
server.stop();
}
}

Creating test suite using Junit and eclipse in selenium

How to create test suite using Junit and eclipse in selenium 

There are some scenarios where we need to run multiple test cases. Either we can run those test cases independently or together. But there are some real time cases where we need to run our test cases in a particular order. In this case we would prefer Test Suite to combine the test cases together and decide their orders and run those.
Below are the steps
1. Create a Test Suite class where we create the Test Suites which will call all the test cases in a particular order.
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite; 
import junit.textui.TestRunner;
public class TestSuite1 extends TestCase {
public static Test suite() 
{ 
TestSuite suite = new TestSuite(); 
suite.addTestSuite( TestCase1.class); 
suite.addTestSuite( TestCase2.class);
suite.addTestSuite( TestCase3.class); 
return suite; 
} 
public static void main(String arg[])
{
TestRunner.run(suite());
}
}
Step 2. Create your first test case 
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase1 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "Suresh");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj"));
}
public void tearDown() throws InterruptedException{
selenium.stop(); 
seleniumServer.stop();
}
}
Step 3. Create your second test case 
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase2 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "Suresh Babu");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Suresh Babu"));
}
public void tearDown() throws InterruptedException{
selenium.stop(); 
seleniumServer.stop();
}
}
Step 4. Create your third test case 
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase3 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "http:/selenium-suresh.blogspot.com");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("
http://selenium-suresh.blogspot.com"));
}
public void tearDown() throws InterruptedException{
selenium.stop(); 
seleniumServer.stop(); 
}

Identify dynamic element in selenium

How to identify dynamic element in selenium 

Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically. Each time id gets generated differently. So to handle this situation we use some JavaScript functions.
starts-with 
if your dynamic element's ids have the format  where button id="continue-12345"  where 12345 is a dynamic number you could use the following
XPath: //button[starts-with(@id, 'continue-')] 
contains 
Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element  can be located based on the ‘suggest’ class without having to couple it with the ‘top’ and ‘business’ classes using the following
XPath: //input[contains(@class, 'suggest')].

using functions in xpath in selenium

How to use functions in xpath in selenium 

Automation using selenium is a great experience. It provides many way to identif an object or element on the web page.
But sometime we face the problems of idenfying the objects on a page which have same attributes. When we get more than
one element which are same in attribute and name like multiple checkboxes with same name and same id. More than one button having
same name and ids. There are no way to distingues those element. In this case we have problem to instruct selenium to identify a perticular
object on a web page.
I am giving you a simple example . In the below html source there are 6 checkboxes are there having same type and same name.
It is really tough to select third or fifth.
input type='checkbox' name='chk' first
input type='checkbox' name='chk' second
input type='checkbox' name='chk' third
input type='checkbox' name='chk' forth
input type='checkbox' name='chk' fifth
input type='checkbox' name='chk' sixth
Thare are some function we can use in Xpath to identify the abject in above cases. An XPath expression can return one of four basic XPath data types:
* String
* Number
* Boolean
* Node-set
XPath Type : Functions
Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()
I will show you how we can use some of these above functions in xpath to identify the objects.
Node Set : last()
In the above html file there are six checkboxes and all are having same attributes (same type and name)
How we can select the last checkbox based on the position. We can use last() function to indentify the last object among all similar objects.
Below code will check or uncheck the last checkbox.
selenium.click("xpath=(//input[@type='checkbox'])[last()]");
How we can select the second last checkbox and third last checkbox. We can use last()- function to indentify the last object among all similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.
selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("xpath=(//input[@type='submit'])[last()-2]");
Node Set : position() 
If you want to select any object based on their position using xpath then you can use position() function in xpath.
You want to select second checkbox and forth checkbox then use below command
selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");
above code will select second and forth checkbox respectively.
String : starts-with() 
Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.
XPath: //button[starts-with(@id, 'continue-')] 
Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having
to couple it with the ‘top’ and ‘business’ classes using the following
XPath: //input[contains(@class, 'suggest')].

WebDriver with TestNG - Gmail Login Functionality

Below is the code for GMAIL Login functionality using WebDriver with TestNG
package com.test.webdriver;
import static org.testng.AssertJUnit.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
  
public class Driver {
private WebDriver driver;
 @BeforeClass
 public void Startup(){
  driver = new FirefoxDriver();
 }
 @Test (description="Google Login")
 public void GoogleLogin() throws Exception{
  driver.get("http://www.gmail.com");
  assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));
  driver.findElement(By.id("Email")).sendKeys("*********");
  driver.findElement(By.id("Passwd")).sendKeys("**********");
  driver.findElement(By.id("signIn")).click();
  Thread.sleep(10000);
  driver.switchTo().frame("canvas_frame");
  driver.findElement(By.id("gbgs4dn")).click();
  driver.findElement(By.id("gb_71")).click();
  driver.switchTo().defaultContent(); 
assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());
 }
@AfterClass
 public void teardown(){
   driver.quit();
 }
}

Selenium Grid - Setup in System

Selenium Grid Setup

1.Check that Java is installed in your system by using the command “java -version”. If Java is installed it will give the output about Java Version that is installed in your system. Else download the Java from Java website (
http://www.java.com/en/download/index.jsp).

2.Check ANT is installed in your system by using the command “ant -version”.If Ant is installed it will give the output about Ant Version that is installed in your system. Else download the Apache Ant from Apache website (
http://ant.apache.org/).
3.Download Selenium Grid from Selenium Grid website(
http://selenium-grid.seleniumhq.org/download.html) and unpack it.

4.Go to the Unpacked directory of the Selenium grid using command prompt and type the command “ant launch-hub”. This will launch the Selenium Grid Hub on a default port “4444” to check whether the selenium grid is running. Type the URL 
http://localhost:4444/console  on your browser and check that you are able to see the selenium hub console on the browser.

5.Now go to the same Selenium Grid directory using command prompt and type the command “ant launch-remote-control”. This will start the Selenium Grid Remote control on default port “5555” and environment “*firefox” and register it to the Hub which you had earlier started.

6. Now after starting the selenium remote control we will test the example provided with Selenium Grid for sequence testing in single machine. For this go to the Selnium grid folder from command prompt and type the command “ant run-in-demo-sequence”. This will execute the test example provided with selenium grid to be executed in sequence.

Now you may had noticed in the setting up steps that I am running the test in sequence. You may think in your mind that, what's special in that? The same things can be achieved when we use a Selenium RC.Then here comes the important part of Selenium Grid. 


Setting up Parallel execution on a single machine


1. Start the hub and one remote control in the same way as in the earlier setting up steps.
2. Now go to the Selenium Grid folder using command prompt and type the command

“ant -Dport =5556 launch-remote-control”

This will start another remote control on port “5556” and register it to the local hub. If you want to register more remote control to the Hub. You can do that by starting multiple remote control but with different ports.

3. To know the no. of registered remote control onto a hub go to the URL 
http://localhost:4444/console. It will give you a view as follows:
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiu0PrtdfsVzw0FCNIXJwHkE8vPPGVmyOcq-a05r2NdrYljpveIMQUtdOJVA00ZzC0bL_IwP4hYZ4zsn6UTqVQRiGAHi214LQgAboMi8YdDeOCYMHU_l0Eg66c6FQ7n-R7jZ7sCLbPRbcs/s1600/HostNames.png
4.Now to run the test in parallel. Go to the selenium grid directory using command prompt and type the command “ant run-demo-in-parallel”. This will run the example tests given with selenium grid in parallel.


Setting up parallel execution for different machines and different environments


In this case start the Hub normally as you do in any of the system. 

For starting the remote control use the following command.

ant -Dport= -Dhost= -DhubURL= -Denvironment= launch-remote-control
Here
“-Dport” should be used to set the port of the remote control.
“-Dhost” should be used to set the host(where the remote control has been started) IP. This is the IP which the hub will use to talk to the remote control.
“-DhubURL” should be used to set the Hub Url where the current remote control will register itself.
“-Denvironment” should be used to set an environment name that remote control represents to the hub.
       Now start 4 different remote controls from 2 different machines and register them to the hub.
  After this check the Hub console. It will look similar to the table as shown below depending upon the remote control that are registered to the Hub.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7r4cKUIWD4TBNmsgbjG-ZaCTWcfNRvQRJhoNbDaymesJogBE59MZTxTOUjhO_M7ek_nJ6J7hrOuTf5IiGoRtP6nHFaqM0W7k7BNVW6HaFIsRAq8ov9X91BW9RqsRZkXg1JrGabvfnVZs/s320/Host.png
Then to verify your set-up go to the Selenium Grid folder from the command prompt and type the command “ant run-demo-in-parallel”

This will run an example test accompanied with the Selenium Grid to run in parallel. 

Advantages of Selenium Grid

1. Remote Execution of the selenium tests can be done using Selenium Grid without actually copying your test code to to remote system.
2. Selenium Grid can be used to save time by executing independent testcases in parallel.
3. Load Testing can be done if we register a lot of remote control to a single hub and execute testcase in parallel to simulate multiple transactions at a single timeperiod.

Technical challenges with selenium

As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.

1.Selenium Supports only web based applications
2.It doesn’t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
3.When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of the test cases
4.Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications
5.There is no object repository concept in Selenium, so maintainability of the objects is very high
6.There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applications
7.Bitmap comparison is not supported by Selenium
8.Any reporting related capabilities, you need to depend on third party tools
9.You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scripting side of selenium

Automation Frameworks

1. What is Test Automation Framework?


Suppose you are given a task where you have to automate some test cases for an application. When you are finished automating the application, what would be your expectations from the scripts you have created? Wouldn’t you want that –

 the scripts should run as intended without any issues.
ü
 the code and the flows should be easy to understand.
ü
 the scripts should be easy to maintain in case of any changes.
ü

All the above points can be achieved by using a proper Automation Framework.

An Automation Framework is a set of guidelines that you can follow during test case scripting to achieve the above mentioned results. This set of guidelines can be anything such as –

 Specifying the folder structure that will be used for storing test cases, function libraries, object repositories and data sheets.
ü
 Deciding the format of the data sheets i.e., how the data sheets would be grouped and how the scripts will access these data sheets.
ü
 Following proper coding standards and using comments so that the code can be understood easily by anyone.
ü
 Using reusable functions wherever possible so that lesser amount of rework is needed in case of any changes
ü
Following the guidelines (that you have set) consistently during the creation of the test scripts would result in the creation of an end product(your Automation Framework) that include all the features which you had targeted for.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqjZlaBAX9I8HuQQ2wf-B2_omzf_S2iSRVIjlVf18jTNPS-exkAnUp6OiVboFyKFf216HmFWxnvoiJo57_Qfazetat2M2_kP22anp6taP3gsllKJXG5twSoLQakbnsiZscqJxfL53kcN8/s320/AutomationFramework.png
Types of Frameworks

1.Keyword framework
2.Datadriven framework
3.Modular framework
4.Hybrid framework.

1.Keyword framework
      In Keyword Driven framework, you can create various keywords and associate a different action or function with each of these keywords. Then you create a Function Library that contains the logic to read the keywords and call the associated action. 
Advantages of Keyword Driven Framework
 The keyword and function libraries are completely generic and thus can be reused easily for different applications.
ü
 All the complexity is added in the function libraries. Once the libraries are ready, it becomes very easy to write the actual test script steps in excel sheets.
ü
Disadvantages of Keyword Driven Framework
 Lot of time and effort needs to be spent initially to create the function libraries. The benefits of the keyword driven framework are realized only after it has been used for longer periods of time.
ü
 Very high programming skills are needed to create the complex keyword library functions.
ü
 It’s not easy for new people to understand the framework quickly.
ü

2.Datadriven framework
      In Data Driven Framework, the data is NOT hard-coded in the test scripts. Instead, it is stored in some external files. The test script first connects to the external data source and then extracts the data from that source. Most of the times, excel sheets are used to store the data. Other external data sources that are frequently used are –
 Text files.
ü
 XML files.
ü
 Databases.
ü
 Combination of more than one external file.
ü
Advantages of Data Driven Framework
 Since the data is kept separate from the test script, the same script can be run multiple times for different sets of data (which can be kept in multiple rows in the data sheet).
ü
 Changes made in the test data don’t affect the test scripts in any way and vice versa.
ü
Disadvantages of Data Driven Framework
 Additional effort and good technical expertise is required to create functions that connect to the external data sources to retrieve the data.
ü
 Additional amount of time is required in identifying which external data source to use and deciding how the data should be stored or grouped in that external data source.
ü

3.Modular framework
    Modular Framework is the approach where all the test cases are first analyzed to find out the reusable flows. Then while scripting, all these reusable flows are created as functions and stored in external files and called in the test scripts wherever required.

Advantages of Modular Framework
 Test Scripts can be created in relatively less time as the reusable functions need to be created only once.
ü
 Effort required to create test cases is also lesser due to code reuse.
ü
 If there are any changes in the reusable functions, the changes need to be done in only a single place. Hence script maintenance is easier.
ü
Disadvantages of Modular Framework
 Since data is still hardcoded in the script, the same test case cannot be run for multiple data values without changing data after each run.
ü
 Additional time is spent in analyzing the test cases to identify with reusable flows.
ü
 Good programming knowledge is required to create and maintain function libraries.
ü

4.Hybrid framework.
      Hybrid Framework is a framework that is created by combining different features of any of the frameworks mentioned above. Based upon your requirements, you can combine the features of any of the above frameworks to come up with your own version of Hybrid Framework.

Advantages of Hybrid Framework
 The main advantage of this approach is that you can use the best features from all the types of frameworks to create your own.
ü
Disadvantages of Hybrid Framework
 The framework is highly complex and needs very good programming expertise and experience to build a Hybrid Framework from scratch.
ü

Android Mobile Automation Testing with Selenium WebDriver

WebDriver with Android Device


Introducing Android WebDriver 
Selenium WebDriver is a browser automation tool which provides a lightweight and elegant way for testing web apps. Selenium WebDriver is now available as an SDK extra in the Android SDK, and supports 2.3 (Gingerbread) and onwards!
Whether or not your site is optimized for mobile browsers, you can be sure that users will be accessing it from their phones and tablets. WebDriver makes it easy to write automated tests that ensure your site works correctly when viewed from the Android browser. We’ll walk you through some basics about WebDriver and look at it in action.
WebDriver(Android Driver) Baciscs
WebDriver tests are end-to-end tests that exercise the web application just like a real user would. WebDriver models user interactions with a web page such as finger flicks, finger scrolls and long presses. It can rotate the display and interact with HTML5 features such as local storage, session storage and the application cache. Those tests run as part of an Android tests project and are based on Junit. They can be launched from Eclipse or the command line. WebDriver tests can be wired with a continuous integration system and can run on phone and tablet emulators or real devices. Once the test starts, WebDriver opens a WebView configured like the Android browser and runs the tests against it. 

Installation of Android SDK
1. Download installer from 
http://developer.android.com/sdk/index.html 
2. Install it to a location (like: C:\Program Files\Android) 
3. Launch “SDK Manager.exe” 
4. It will launch “Android SDK and AVD Manager”. By default “Installed packages” will be highlighted. On the pop up “Choose Packages to install”, there will be some packages selected already. Go ahead with the “Install”.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixMMyhNI5qMd8o567C8Q26-_ZvaYehhtbYlrKCxZ2DLhK9gHWc6Gc_C1BgOcfio6H3OBXgSXiUpdtU2mfFzfnQ0bzo8ocCXbJ8kriNAZVGO3un2qDgkJjcjjDL5iIvBZR1FwEjc_2lBlU/s320/AVD+Manager.png

5. Once it is done, select “Virtual Devices” to create one for you. Click on “New” and enter some name. Target as “Android 2.2 – API Level 8” (or) select from dropdown. Select Size as “512” and “Built-in” to be “WVGA854” and click on “Create AVD”.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbyQeml2qWCpe1aFoWm_054WqtkPmfUrdlhiU6mSbxZlbdCIRf6URwQM6o6pOIl6yEtY692NMRQjXIvNT-iGvityjs-qkvBjalMGbTHvaBuI2MoX0XrmCwFvy2aN8TSmzt-nSqXKui3Gg/s320/AVD+Manager+start.png

6. Once done select the Virtual device you created and click on Start. You can find the “Start” button on the right panel in the above shown image. Clicking “Start” will launch another pop-up, just say “Launch” and proceed.
7.Once its opened you can see the image as below
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAkxdYdDWqoMypMoyoFNXFhABO5tqN8KI9IZeReF6CVvOXWOikEKAGUpXoqQdfdZ2zaKYXpUginl-5sz96-Lii49IlZMxOfWjIsW5RE5Uow-l2zd9ndM3Wb_UhDg2XD3S8rkTbs5iiwdk/s320/Android+Virtual+Mobile.png

Install webdriver APK in Android Device 
1. Download “android-server-2.0.2rc3.apk ” from the following location http://code.google.com/p/selenium/downloads/list
2. Copy the above downloaded file into folder “C:\Program Files\Android\android-sdk\platform-tools”
3. Run the “Command Prompt” as administrator.
4. Execute “cd C:\Program Files\Android\android-sdk\platform-tools”
5. Execute the command “adb install android-server-2.0.2rc3.apk”
6. We also need to set up Port forwarding, run the command “adb forward tcp:8080 tcp:8080"
7. Click on the WebDriver app on Emulator and this will make the android server available at “http://localhost:8080/wd/hub”. Opening this URL in Firefox will show up a blank page on success.
8. Confirm the following settings on your emulator: Settings -> Applications -> Development -> Check "USB debugging", "Stay Awake" and "Allow mock locations".
9. Launch the emulator, it will have Webdriver installed. When you launch the Webdriver, it will confirm “jetty started”
10.WebDriver installed successfully as shown in below image.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8YLhltXY-Nsv8e9FA5BJZmzy5qH4ef0DnQWJOizDSsuYb104PtpKDcOuJQt5NX2giThWHkLr8J82QGvIn-TQIyonAWklwViftxP4We1DoUvo3sf1NKUDwmS6vS5afR-l5zqtAf5XUsko/s320/WebDriver+in+Android+virtual+device.png

Open the eclipse and try with below examples.
TC – Gmail Login
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.android.AndroidDriver;
public class Gmail {
public static void main(String args[])throws Exception
{
AndroidDriver ad=new AndroidDriver();
System.out.println("Started");
ad.get("http://www.gmail.com");
System.out.println("Application Title"+ ad.getTitle());
Thread.sleep(2000);
ad.findElement(By.name("Email")).sendKeys("type your email");
ad.findElement(By.name("Passwd")).sendKeys("type password");
ad.findElement(By.name("signIn")).click();
System.out.println("Opened");
ad.close();
 }
}

ANT-Generating Selenium HTML and XSLT reports using TestNG-xslt through Ant

Selenium – Use Ant to Generate HTML and XSLT Reports
Apache Ant is an open source build tool. A build tool can be used to compile the source code, creating the build artifacts such as JAR, WAR, and EAR files. Some of the other usage of ANT is to run unit tests, do the application deployment on containers such as JBoss, Tomcat, WebSphere, WebLogic, GlassFish, etc, and to run Automated Selenium Tests.
Ant is a powerful build tool and also is very much extensible. There are several open source Ant libraries available which need to be just downloaded, unzipped, and copied (JAR file) into the Ant’s “lib” folder. Once the library file is copied, then we can utilize the “Tasks” in the Ant’s build.xml file. Ant’s “contrib library, jsch library, etc” are the best examples for such libraries.
Install and configure ANT
1. Download ANT from Apache web site – ANT download link
2. Unzip the ant and copy to C:\Ant folder
3. Now we need to configure environment variables: ANT_HOME 
4. Navigate to environment variables and click on new button. 
5. Enter Variable name as ANT_HOME and Variable Value as C:\apache-ant-1.8.4.Then click on OK button
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSU8N7W7_oM2MtI9_W5eqXP_I1ox288wgzjPaNPYpMIMkyPDmvauEXjnlz7AMGkybodiRI5mGscz2vvijXYTHi3gnuxP1DaCCcIBpTNfot9WJl5Vq8cBixdFPAQC7qW9K7kqzQHSYqzV4/s1600/ANT_HOME.png
6. Now select the PATH and click on EDIT button
7. Now give the semicolon (;) at the end and add ANT path up to bin folder
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhua8xiir-kNS42ADpMe-0BmQDxMtDCGSGdTHB37KXVL9vEZ1hjyZRtrHlGmQxFdgZ7HcxaZo_elMzRRCiKdolWZyE5SzgmaItaEbDsut03xsklhyphenhyphenAb4FkuhSYt2WXs8tN1Pt8CNhmjBOA/s1600/PATH.png
8. Now click on OK button and go to command prompt and type ANT.
“It will give message as build.xml not fount”
9. Now go to eclipse and add below build.xml file to your selenium project.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5A1wRTmAspP02qpdXcgyTcMfcvpPr9uZuSm5nR06gPOZqtM_y7GisbgUh1sq614DKwWfO1BsrU7n9pYUF3vt7vgkFq-uDu_h_Jga8_VB9UJK76jXr3GyDycOGbwrYOCEOPSqvFjcoUDo/s320/build.XML+File.png

Build.xml file code
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvLuTJXt22ecBL4zvAvi41x_OuuuYJox8UtW_rrgVekTr_ppfuHc99aJ_GXsGM0RsZHd6RO6dxasy6ttv_ZqC4lTa6apwjsuOgmgj0bUreimLITJ9mNCgb9hK9qVvt2E-t0uc3Syum1qw/s320/build.XML+Code.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUU1cqikGWoTZycXItyEfv4bfCGPgtLE6L-STVaQDXTWjUJoYQ6-hwPg_GYkZ_kudtfBzHd7yfbGdFpDX8MmknZCNmnIaVGpFMWK-v7FO9hEQAY3BrWUj3fpHMmwuelXYQTv4qTP014mQ/s320/build.XML+Code1.png
10. In this Build.xml file give the path where you copied all the required jar file.(Copy all the required jar files in any of the folder and mention that path)
11. Now go to command prompt and type > ant clean
It will clean all the required files related to ant.
12. Now type > ant compile
It will compile your code
13. Now type >ant run 
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijMAPXBWSa84pUttPGtj1Ay5EqNuy_xlg-4eSN1aVWJX4RdUsj1DUwHdSFJT47XokPQI-1EKo3F9Tabhuhykn0R6sUFb1KUeuLzg3j9_QiqWZpPYSZR_tyVJeCJOPG34KWYtvQMFsw_w0/s320/ANT-TestNG-HTML+Report.png
It will run your program and will generate HTML reports.
Generating selenium reports using TestNG-xslt through Ant 
TestNG-xslt generates user friendly reports using the TestNG results output (testng-results.xml). Its uses the pure XSL for report generation and Saxon as an XSL2.0 implementation
For generating testng-xslt report for your project do the following:
1. Download the testng-xslt
2. Unzip and copy the testng-results.xsl from the testng-xslt folder(testng-xslt-1.1\src\main\resources) to your own project folder.
3. Now copy the saxon library from (testng-xslt-1.1\lib\saxon-8.7.jar)to where you created a folder for which you copied all the JAR files to run ANT.
4. Modify your build.xml of ant and add the following target to it.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizXCIphWzAquV3z8yBP9hIAqfvzvxrzHBwn25auwNrmeMpZdTzPOVTXdlNmV4rjBtr7E007YjSZSpt7cIpsjfpo7a9nSXRs3jbJcimhTQgw0ZYnKYQ-zAjmyzVbnouhSP482eBechYhRs/s320/XSLT+code.png
5. Now go to command prompt and follow below steps to generate XSLT reports.
6. Now type > ant clean
It will clean all the required files related to ant.
7. Now type > ant compile
It will compile your code
8. Now type >ant run 
It will run your program.
9. Now type >ant xsltreports
It will generate xslt reports as below
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJGAT-1zVyCy1DCnTvb9Cp1BndJhQ-YdL35jbsLUuAoJwjZ-BruwSz7nTIW3MiKQbhKkvvcdneS-k9xJFazu4mrl-RHqhfBSmYq7SOKzMThZ5Y0Y3fgIiIAa7Xw_2kHuztnpgYtjkQmqM/s320/ANT-TestNG-XSLT+Report.png

Steps to Configure Selenium WebDriver in Android Device

Steps to Configure Selenium Web Driver in Android Device
1. Install  Android SDK 
Download the SDK zip file and unzip in your local computer.
Say download at “C:\android ” location
Go to unzipped folder and click on “Android SDK Manager” and install the following:
         a.Tools
         b.Extras
         c.Android API’s as per your choice (Say Android 2.2 , Android 4.0)

2. Install the ADT Plugin for Eclipse-
Goto Help > Install New Software....>> Add
3.Configure ADT Plugin
Window > Preferences...>>Android
Set the SDK location to where is your Android SDK has been installed.
Location will be something like:  C:\android\android-sdk-windows

4. Add the new AVD
In Eclipse goto Window >>AVD Manager>>
Create new AVD by clicking on “New” button.(Give the AVD  name  and select the Target)

5.Now download the Android APK 
Copy the file and paste it in the “Platform-tools” folder of the unzipped Android SDK.
Location will be something like “C:\android\android-sdk-windows\platform-tools 

6. Now start the Android AVD (Which has been created in Step 4) by following below in your Eclipse
Window >>AVD Manager>> Select the created AVD and click on “Start”

7.  Find the installed emulator device id .
open the command prompt ( cmd ) and run the following command 
adb devices
Emulator device id will be something like “emulator-5554

8. Now from the command prompt, go to the “Platform-tools” folder of the unzipped Android SDK
cd "C:\android\android-sdk-windows\platform-tools"

9. Install the Android server by running the following command
adb -s emulator-id -e install -r  android-server-2.21.0.apk

10. Start the Android WebDriver application by running the following command
adb -s emulator-id shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity -e debug true

11. Now setup the port forwarding in order to forward traffic from the host machine to the emulator by running the following command
adb -s emulator-id forward tcp:8080 tcp:8080

Selenium Database Connectivity

Prerequisites:

Download - mysql-connector-java-5.1.0-bin.jar and add it to your project
Create a table with some data

Snippet:

import java.sql.*;
import javax.sql.*;

public class dbconnection
{
public static void main(String args[])
{
String email;
String dbUrl = "jdbc:mysql://localhost:3306/test";  //This URL is based on your IP address
String username="username"; //Default username is root
String password="password"; //Default password is root
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select email from users where user_id = 1;";

try 
{

Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl,username,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) 
{
dbtime = rs.getString(1);
System.out.println(email);
} //end while

con.close();
} //end try

catch(ClassNotFoundException e) 
{
e.printStackTrace();
}

catch(SQLException e) 
{
e.printStackTrace();
}

}  //end main

}  //end class

WebDriver Interview Questions and answers


1.  Difference between Absolute path & Relative path.
Absolute path will start with root path (/) and Relative path will from current path (//)
Absolute xPath : /html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div[@id='main']/div[@id='Blog1']/div[1]/div[1]/div/div[1]/div/h3/a

Relative xPath : //h3/a[text()='Working on New Window']
2.  Tell me some TestNG Annotations.
@Test,@Parameters,@Listeners,@BeforeSuite,@AfterSuite,@BeforeTest,@AfterTest,
@DataProvider,@BeforeGroups,@AfterGroups,@BeforeClass,@AfterClass,
@BeforeMethod,@AfterMethod,@Factory

3.  What are desiredcapabilities?
Desired Capabilities help to set properties for the Web Driver. A typical use case would be to
set the path for the Firefox Driver if your local installation doesn't correspond to the default
settings.
4.  Difference between Selenium RC and Selenium Web driver.
 Difference between Selenium RC and Selenium Web driver.

Selenium RC
Selenium Web driver
Selenium RC’s architecture is way more complicated.
Web Driver’s architecture is simpler than Selenium RC’s.
Selenium RC is slower since it uses a JavaScript program called Selenium Core.This Selenium Core is the one that directly controls the browser, not you.
Web Driver is faster than Selenium RC since it speaks directly to the browser uses the browser’s own engine to control it.
Selenium Core, just like other JavaScript codes, can access disabled elements.
Web Driver interacts with page elements in a more realistic way.
Selenium RC’s API is more matured but contains redundancies and often confusing commands.
Web Driver’s API is simpler than Selenium RC’s. It does not contain redundant and confusing commands.
Selenium RC cannot support the headless HtmlUnit browser. It needs a real, visible browser to operate on.
Web Driver can support the headless HtmlUnit browser.
Selenium RC Has Built-In Test Result Generator. Selenium RC automatically generates an HTML file of test results. 
Web Driver has no built-in command that automatically generates a Test Results File.
Selenium RC needs the help of the RC Server in order to do so.
web Driver directly talks to the browser
Selenium RC can support new browsers
It cannot readily support new browsers
5.  Difference between Web driver listener and  TestNG Listener.
TestNG and Web driver Listener have different interfaces to implement and call them. They both
modify respective behaviour. You can use Listeners in Annotation. Below 2 URL gives the
 detailed  list of listener and their interfaces.
6. Describe your framework.
Refer automation link
7.  Which is the best way to locate an element?
Finding elements by ID is usually going to be the fastest option, because at its root, it eventually calls down to document.getElementById(), which is optimized by many browsers.

Finding elements by XPath is useful for finding elements using very complex selectors, and is the most flexible selection strategy, but it has the potential to be very slow, particularly in IE. In IE 6, 7, or 8, finding by XPath can be an order of magnitude slower than doing the same in Firefox. IE provides no native XPath-over-HTML solution, so the project must use a JavaScript XPath implementation, and the JavaScript engine in legacy versions of IE really is that much slower.


If you have a need to find an element using a complex selector, I usually recommend using CSS Selectors, if possible. It's not quite as flexible as XPath, but will cover many of the same cases, without exhibiting the extreme performance penalty on IE that XPath can.
8.  Why we refer Firefox driver to the web driver  inheritance. 
web Driver driver = new FireFoxDriver();
WebDriver is an interface which contain several abstract methods such as get(...), findElamentBy(...) etc.
We simply create reference of web Driver and we can assign objects (Firefox driver, CromeDriver, IEDriver, Andriod driver etc) to it.
Ex :
WebDriver driver = new FireFoxDriver();-----------(1)
If we are using (1) we can do the same thing by using
FireFoxDriver driver = new FireFoxDriver();---------(2)
We can use (1) and (2) for same purpose but if we want to switch to another browser in same program
then again we have to create the object of other class as for example
CromeDriver driver = new CromeDriver();.
creating object of several class is not good. So we create the reference of WebDriver and
we assign the objects of another class as for example
WebDriver driver; // it is created only one time in the program
driver = new FireFoxDriver();// any where in the program
driver = new CromeDriver(); // any where in the program
9.  What are the features of TestNG?
TestNG is a testing framework designed to simplify a broad range of testing needs, from
unit testing (testing a class in isolation of the others) to integration testing (testing entire
systems made of several classes, several packages and even several external frameworks,
 such as application servers). You can use test suite,annotations, automatically generation
 of report and much more.
10.   What is the difference between thread.Sleep()  and selenium. Set Speed ("2000")?
If the application is taking time to load the page then we use selenium.waitforpageload(" "). This command is doesn’t wait upto the given time whenever the page load is completed.
If the application is taking time to refresh the page, then we use Thread. Sleep ( ).it is a standard wait it simply wait to the given time.
selenium.setSpeed
 1. Takes a single argument in string format
 Ex: selenium.setSpeed("2000") - will wait for 2 seconds
 2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in set Speed.
 thread.sleep
 1. Takes a single argument in integer format
 ex: thread. Sleep(2000) - will wait for 2 seconds
 2. Waits for only once at the command given at sleep.
11.   In what situation selenium finding element get fails?
-->Element loading issue
-->Dynamic id of web element
12.   What is the difference between "GET" and "NAVIGATE" to open a web page in selenium web driver?
Get method will get a page to load or get page source or get text that's all whereas navigate
 will guide  through the history like refresh, back, forward.For example if we want to move
forward and do some functionality and back to the home page this can be achieved
through navigate() only. driver.get will wait  till the whole page gets loaded and driver.navigate
will just redirect to that page and will not wait
13.   Please tell me the difference b/w implicitly Wait and Explicit wait.
Implicit Wait sets internally a timeout that will be used for all consecutive Web Element searches. It will try lookup the element again and again for the specified amount of time before throwing a NoSuchElementException if the element could not have been found. It does only this and can't be forced into anything else - it waits for elements to show up.


Explicit Wait or just Wait is a one-timer used by you for a particular search. It is more extendible in the means that you can set it up to wait for any condition you might like. Usually, you can use some of the prebuilt Expected Conditions to wait for elements to become clickable, visible, invisible, etc., or just write your own condition that suits your needs.
14.   How we can retrieve the dynamically changing Ids? 
When we login Facebook the login label's id
changes dynamically thus resulting in failure.
We have a hierarchy of locators and Facebook Is dynamic in nature,so we are not able to
use "id" for  identification for after that we have remaining 7 locator's for that :2. xpath ()..
3. name..4. css.. 5. link text.. 6. partiallinktext...7.tag name. so u can use any one for
 identifying it. Most probably u can use "xpath" or  "css-locator" and if there r tag then
link text or partial-link text. it depend on u . But we never use id's in Ajax application
 because it’s not possible.
15.What is the difference between driver.Close()  and driver.Quit () method?
Close() - It is used to close the browser or page currently which is having the focus.
Quit() - It is used to shut down the web driver instance or destroy the web driver instance
(Close all the windows)
16.   How to scroll web element?--not browser—
FirefoxProfile profile=new FirefoxProfile();
profile.setEnableNativeEvents(true);
WebDriver driver=new FirefoxDriver(profile);
driver.navigate("http://jqueryui.com/draggable/");
Thread.sleep(6000L);
WebElement element=driver.findElement(By.xpath("//div[@id='draggable']"));
Actions actn=new Actions(driver);
actn.dragAndDropBy(element, 50, 50).build().perform();
}
17.   What is the basic use of Firefox profiles and how can we use them using selenium?
A profile in Firefox is a collection of bookmarks, browser settings, extensions, passwords,
and history; in short, all of your personal settings.
We use them to change user agent, changing default download directory, changing versions etc.
18.   Customize the name of file going to be downloaded?
You have to download AUTO IT.exe file and has to be install
and later you have create .au3 file (in this file you have to specify the commands in
 VB script  like your file  name, where have to save, it will be easy may be 3 or 4 steps )
using AUTOIT...then right click the .au3 file you have to compile ....after that you will
get the .exe file with the name of .au3 file ..In eclipse you will give the code like this
<----processbuildder .exe="" .start="" au3="" file="" of="" path="" processbuilder="" ps="new" the="">
19.   How to handle internationalisation through  web driver?
FirefoxProfile profile = new FirefoxProfile();
profile.set Preference("intl.accept_languages","jp");
Web driver driver = new FirefoxDriver(profile); driver.get(google.com) will open google in
Japanese Lang
20.   How to overcome same origin policy through web driver?
Proxy server.
DesiredCapabilities capability=new DesiredCapabilities.firefox();
capability.setCapability(CapabilityType.PROXY,"your desire proxy")
WebDriver driver=new FirefoxDriver(capability);

21. How to put text in Facebook search box using  selenium web driver.
driver.findElement(By.xpath("//div[contains(@class, '_586i')]")).sendKeys("abc");


22. Difference between flex and flash application.
In flash there is no code just based on creativity(design) we will complete the
work(time consuming process) whereas flex contain some small functions
which is integrated with mxml,PHP..(no tool is there to develop
 flex we want to use the properties of css and style sheet)
23. What is Error Collector in TestNG? What is its use?
This class allows the collection of errors during the process of retrieving the
test data for the test method parameters


24. How can we get the font size, font color, font type used  for a particular text on a web page using Selenium web driver?
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-colour);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-type);
driver.findelement(By.Xpath("Xpath ").getcssvalue("background-colour);
25. How to run tests in multiple browser parallel? Is there  any other option other than selenium grid?
26. How to prepare Customized html Report using  TestNG  in hybrid framework.
Below are the 3 ways:
• Junit: with the help of ANT.
• TestNG: using inbuilt default.html to get the HTML report. Also XST reports from ANT,
Selenium, TestNG combination.
• Using our own customized reports using XSL jar for converting XML content to HTML.
27. “What’s the hierarchy of TestNG annotations?  Explain me about annotation hierarchy & execution  order?
Please find hierarchy below:
1.      org.testng.annotations.Parameters (implements java.lang.annotation.Annotation)
2.      org.testng.annotations.Listeners (implements java.lang.annotation.Annotation)
3.      org.testng.annotations.Test (implements java.lang.annotation.Annotation)
4.      org.testng.annotations.AfterMethod (implements java.lang.annotation.Annotation)
5.      org.testng.annotations.BeforeTest (implements java.lang.annotation.Annotation)
6.      org.testng.annotations.BeforeMethod (implements java.lang.annotation.Annotation)
7.      org.testng.annotations.Optional (implements java.lang.annotation.Annotation)
8.      org.testng.annotations.AfterTest (implements java.lang.annotation.Annotation)
9.      org.testng.annotations.Guice (implements java.lang.annotation.Annotation)
10.  org.testng.annotations.BeforeGroups (implements java.lang.annotation.Annotation)
11.  org.testng.annotations.ExpectedExceptions (implements java.lang.annotation.Annotation)
12.  org.testng.annotations.TestInstance (implements java.lang.annotation.Annotation)
13.  org.testng.annotations.NoInjection (implements java.lang.annotation.Annotation)
14.  org.testng.annotations.AfterSuite (implements java.lang.annotation.Annotation)
15.  org.testng.annotations.AfterClass (implements java.lang.annotation.Annotation)
16.  org.testng.annotations.AfterGroups (implements java.lang.annotation.Annotation)
17.  org.testng.annotations.DataProvider (implements java.lang.annotation.Annotation)
18.  org.testng.annotations.BeforeSuite (implements java.lang.annotation.Annotation)
19.  org.testng.annotations.BeforeClass (implements java.lang.annotation.Annotation)
20.  org.testng.annotations.Factory (implements java.lang.annotation.Annotation)
21.  org.testng.annotations.Configuration (implements java.lang.annotation.Annotation)
22.  org.testng.annotations.ObjectFactory (implements java.lang.annotation.Annotation)
28. How the TestNG interacts with Selenium Core?
Explain me steps and internal architecture?"

29. Is it possible test web services using selenium?
Using Jmeter we can test how one website is talking to each other means time taken to
send data, feeds, messages from one website to other website. Jmeter does a nice job
of doubling for performance and api tests.
30. How to refresh a page without using context click?
1.Using sendKeys.Keys method
2.Using navigate.refresh() method
3.Using navigate.refresh() method
4.Using get() method
5.Using sendKeys() method
1.Using sendKeys.Keys method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);

2.Using navigate.refresh() method
driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/100-selenium-interview-questions.html");
driver.navigate().refresh();

3.Using navigate.to() method
driver.get("http://ruchi-myseleniumblog.blogspot.in/2014/01/selenium-hybrid-framework-using.html");
driver.navigate().to(driver.getCurrentUrl());

4.Using get() method
driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/basic-core-java-interview-questions.html");
driver.get(driver.getCurrentUrl());

5.Using sendKeys() method
driver.get("https://accounts.google.com/SignUp");

driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
31. Can u send a code for printing in selenium?
There are two cases:
Case1. Any hyperlink/button on a web page, n clicking that link/button a print dialog box
opens. (Performing an action on web page)
Case2.or do u want to open print dialog box within ur own script, not by performing any
action on web page.
So If Case 1: just a call for WebElement.click() event will work to open it.
If Case 2: Call a Printer Job object (Use Awt API).
For code: Google it.
32. How to find broken images in a page using  Selenium Web driver.
1. Get xpath and then using tag name; get all the links in the page
2. Click on each and every link in the page
3. In the target page title, look for 404/500 error.
33. How to handle Ajax popup window?
By using getWindowHandles() and obj.switchTo.window(windowid) we can handle popups using
explicit wait and driver.swtchT0.window("name") commands for your requirements.

34. How to handle auto complete box in web driver?
By typing in box and capturing list elements
driver.findElement(By.id("your searchBox")).sendKeys("your partial keyword");
Thread.sleep(3000);
List listItems = driver.findElements(By.xpath("your list item locator"));
listItems.get(0).click();
driver.findElement(By.id("your searchButton")).click();
35. How to get the name of browser using Web Driver?
public class JsExecute
{
WebDriver driver;
JavascriptExecutor js;
@Before
public void setUp() throws Exception
{
driver=new FirefoxDriver();
driver.get("http://www.google.com");
}
@Test
public void test()
{
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return navigator.appCodeName"));
}}
OR
String s = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");
System.out.println("Browser name : " + s);
36. How to handle colors in web driver?
Use getCssValue(arg0) function to get the colors by sending 'color' string as an argument.
Example
String col = driver.findElement(By.id(locator)).getCssValue("color");

37. How to pass parameters from testng.xml into  test case.
package programs;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Parallelexecution {

 private WebDriver driver = null;

 @BeforeTest
 @Parameters({ "BROWSER" })
 public void setup(String BROWSER) {
  System.out.println("Browser: " + BROWSER);

  if (BROWSER.equals("FF")) {
   System.out.println("Firefox Browser is selected");
   driver = new FirefoxDriver();
  } else if (BROWSER.equals("IE")) {
   System.out.println("Internet Explorer Browser is selected");
   driver = new InternetExplorerDriver();
  } else if (BROWSER.equals("HU")) {
   System.out.println("Html Unit Browser is selected");
   driver = new HtmlUnitDriver();
  } else if (BROWSER.equals("CH")) {
   System.out.println("Google chrome Browser is selected");
   driver = new ChromeDriver();
  }
 }

 @Test
 public void testParallel() throws Exception {
  driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/100-selenium-interview-questions.html");

 }
}


above sample program BROWSER is a variable which value would be passed from TestNG.xml and TestNG.xml and it will run the test multiple time each time BROWSER value would be set with different browser name and test will check the BROWSER value and decide which browser test will run.
                                                 

38. How to get text from captcha image??
driver.findElement(By.xpath(".//*[@id='SkipCaptcha']")).click();
String attr = ie.findElement(By.xpath(".//*[@id='SkipCaptcha']")).getAttribute("value");
System.out.println("The value of the attribute 'Name' is " + attr);

39. Is there a way to click hidden LINK in web driver?
String Block1 = driver.findElement(By.id("element ID"));
JavascriptExecutor js1=(JavascriptExecutor)driver;
js1.executeScript("$("+Block1+").css({'display':'block'});");

40. What Class Extends Web Driver?
AndroidDriver, ChromeDriver, EventFiringWebDriver, FirefoxDriver, HtmlUnitDriver,
InternetExplorerDriver, IPhoneDriver, PhantomJSDriver, RemoteWebDriver, SafariDriver

41. What are the APIs that support Web Driver?
API are  nothing but collection of all selenium commands for Locating UI Elements
(WebElements),Fetching a Page,User Input  etc…

42. How to disable cookies in browser.
Using deleteAllVisibleCookies() in selenium

43. "We have heard about frameworks well it can be
 broadly classified into these TDD, BDD and ATDD frameworks .What’s the Difference?"

44. How to change user agent in Firefox by selenium  web driver.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UA string");
Web Driver driver = new FirefoxDriver(profile);

45. What is Selenese?
Selenese is HTML language based command, which is used in Selenium IDE.
46.Differences between QTP and selenium.
1) Selenium generates a proxy while starting browser. QTP does not
2) QTP uses only Vb script. Selenium is available in many languages
3) QTP is paid and selenium is free.
4) You can run script from a particular line in QTP but in selenium, you cannot.
5) Selenium works on all browsers. QTP only works on IE, mozilla. Support from chrome has been introduced lately.
6) QTP is more organized and user friendly
7) Selenium requires more technical skills
8) QTP can also be used on desktop based applications but selenium cannot be used
47. What is the MOST challenging test problem in my career in Automation?
In my career
Changing XPATHS' between testing server and production server-by keeping generic xpath
Keep separate property files for production and UAT
automating flash apps
Mobile Automation

48. “Suppose developer changed the existing image to new image with same xpath. Is test case pass or fail?"
Pass

49. How to handle network latency using selenium? 
Using driver.manage.pageLoadingtime for network latency

50. How does u handle dynamic elements without using  xpath (with example?)
By using classname or css.

51. What are the different types of driver implementation?
AndroidDriver, AndroidWebDriver, ChromeDriver, EventFiringWebDriver, FirefoxDriver, HtmlUnitDriver, InternetExplorerDriver, IPhoneDriver, IPhoneSimulatorDriver, RemoteWebDriver, SafariDriver, WebDriverBackedSelenium

52. Code for Opening Firefox browser?
Webdriver driver=new FireFoxdriver();

53. Which repository you have used to store the test  scripts?
I have created scripts in excel file and store them in Test cases folder under src .
54. How to work with radio button in web driver?
We can select the value from the drop down by using 3 methods.

selectByVisibleText - select by the text displayed in drop down
selectByIndex  - select by index of option in drop down
selectByValue  - select by value of option in drop down




WebElement e = driver.findElement(By.id("44"));
Select selectElement=new Select(e);
// both of the below statements will select first option in the weblist
selectElement.selectByVisibleText("xyz"); 
selectElement.selectByValue("1");

55. How to work with dynamic web table?
You can get the total number of tags within a tag by giving the xpath of the
  element by using  this function -
List ele = driver.findElements(By.xpath("Xpath of the table"));
Now you can use a for each loop to loop through each of the tags in the above list
and then read each  value by using getText() method.

56. Detail about TestNG Test Output folder.
It is the directory where reports are generated. Every time tests run in a suite, TestNG
creates index.html and  other files in the output directory.

57. In frame if no frame Id as well as no frame  name then which attribute I should consider  throughout our script.
You can go like this.....driver.findElements(By.xpath("//iframe"))...
Then it will return List of frames then switch to each and every frame and search for
 the locator which you want then break the loop

58. What is object repository?
It is collection of object names their properties, attributes and their values .It maye be
 excel, XML,property file or text file

59. TestNG vs. Junit?
Advantages of TestNG over Junit
In Junit we have to declare @BeforeClass and @AfterClass which is a constraint where as in TestNG there is no constraint like this.
-->Additional Levels of setUp/tearDown level are available in TestNG like @Before/AfterSuite,@Before/AfterTest and @Before/AfterGroup
No Need to extend any class in TestNG.
There is no method name constraint in TestNG as in Junit. You can give any name to the test methods in TestNG
-->In TestNG we can tell the test that one method is dependent on another method where as in Junit this is not possible. In Junit each test is independent of another test.
Grouping of testcases is available in TestNG where as the same is not available in Junit.
-->Execution can be done based on Groups. For ex. If you have defined many cases and segregated them by defining 2 groups as Sanity and Regression. Then if you only want to execute the “Sanity” cases then just tell TestNG to execute the “Sanity” and TestNG will automatically execute the cases belonging to the “Sanity” group.
Also using TestNG your selenium test case execution can be done in parallel.

60. What is the difference between @before method and @beforeclass.
In JUnit4 @Before is used to execute set of preconditions before executing a test.
 For example, if there is a need to open some application and create a user before
executing a test, then this annotation can be used for that method.  Method that is
marked with @Before will be executed before executing every test in the class.
If a JUnit test case class contains lot of tests which all together need a method
which sets up a precondition  and that needs to be executed before executing the
Test Case class then we can utilise “@BeforeClass” annotation.

61. What are the different Parameters for @Test annotation? 
Parameters are keywords that modify the annotation’s function.

62. Can we run group of test cases using TestNG?
Test cases in group in Selenium using TestNG will be executed with the below options.
 If you want to execute the test cases based on one of the group like regression test or smoke test
 @Test(groups = {"regressiontest", "smoketest"})


63. Differences between Selenium web driver, IDE and RC?
64. How to highlight an object like qtp/uft does through selenium and java?

How to highlight an object with selenium and java

How to highlight an object like qtp/uft does through selenium and java?
public void highlightElement(WebDriver driver, WebElement element) {
for (int i = 0; i < 2; i++)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;");
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
}}
Call the highlightElement method and pass webdriver and WebElement which you want to highlight as arguments.
65. What are the different assertions in SIDE?
Assertions are like Assessors, but they verify that the state of the application conforms
 to what is expected. Examples include "make sure the page title is X" and "verify that this
 check box is checked".
All Selenium Assertions can be used in 3 modes: "assert", "verify", and "waitFor".

 For example, you can "assertText", "verifyText" and "waitForText". When an "assert" fails, the test is aborted. When a "verify" fails, the test will continue execution, logging the failure. This allows a single "assert" to ensure that the application is on the correct page, followed by a bunch of "verify" assertions to test form field values, labels, etc.

"waitFor" commands wait for some condition to become true (which can be useful for testing Ajax applications). They will succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the current timeout setting (see the setTimeout action below).

66. How to store a value which is text box using  web driver?
driver.findElement(By.id("your Textbox")).sendKeys("your keyword");

67. How to handle alerts and confirmation boxes. Confirmation boxes and Alerts are handled in same way in selenium.
var alert = driver.switchTo().alert();
alert.dismiss();  //Click Cancel or Close window operation
alert.accept();   //Click OK
Handle Confirmation boxes via JavaScript,
driver.executeScript("window.confirm = function(message){return true;};");

68. How to mouse hover on an element?
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform();

69. How to switch between the windows?
private void handlingMultipleWindows(String windowTitle) {
            Set windows = driver.getWindowHandles();
            for (String window : windows) {
                driver.switchTo().window(window);
                if (driver.getTitle().contains(windowTitle)) {   return;   }     }     }

70. How to switch between frames?
WebDriver's driver.switchTo().frame() method takes one of the three possible arguments:
Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index "0", the second at index "1" and the third at index "2". Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.
Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.
Select a frame using its previously located WebElement.
Get the frame by it's id/name or locate it by driver.findElement() and you'll be good.
71. What is actions class in web driver?
Actions class with web Driver help is Sliding element, Resizing an Element, Drag & Drop,
hovering a mouse, especially in a case when dealing with mouse over menus.
Dragging & Dropping an Element:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testDragandDrop {
  public static void main(String[] args) throws InterruptedException {
   WebDriver driver = new FirefoxDriver();
  driver.get("http://jqueryui.com/resources/demos/droppable/default.html"); 
  WebElement draggable = driver.findElement(By.xpath("//*[@id='draggable']"));
  WebElement droppable = driver.findElement(By.xpath("//*[@id='droppable']"));   
  Actions action = new Actions(driver); 
action.dragAndDrop(draggable, droppable).perform();
  }
}
Sliding an Element:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testSlider {
  /**
  * @param args
  * @throws InterruptedException
  */
 public static void main(String[] args) throws InterruptedException {
   WebDriver driver = new FirefoxDriver();
  driver.get("http://jqueryui.com/resources/demos/slider/default.html"); 
  WebElement slider = driver.findElement(By.xpath("//*[@id='slider']/a")); 
  Actions action = new Actions(driver);
  Thread.sleep(3000);
  action.dragAndDropBy(slider, 90, 0).perform();
  }
}
Re-sizing an Element:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class testResizable {
  public static void main(String[] args) throws InterruptedException {
   WebDriver driver = new FirefoxDriver();
  driver.get("http://jqueryui.com/resources/demos/resizable/default.html");
    WebElement resize = driver.findElement(By.xpath("//*[@id='resizable']/div[3]")); 
  Actions action = new Actions(driver);
  action.dragAndDropBy(resize, 400, 200).perform();
    }
}
72. Difference between the selenium1.0 and selenium 2.0?
Selenium 1 = Selenium Remote Control.
Selenium 2 = Selenium Web driver, which combines elements of Selenium 1 and Web driver.

73. Difference between find element () and findelements ()?
findElement() :
Find the first element within the current page using the given "locating mechanism".
Returns a single WebElement.
findElements() :
Find all elements within the current page using the given "locating mechanism".
Returns List of Web Elements.
findElement() :
Find the first element within the current page using the given "locating mechanism".
Returns a single WebElement.
Syntax: WebElement findElement(By by)
Ex:
driver.get("http://ruchi-myseleniumblog.blogspot.in/"); 
WebElement widget = driver.findElement(By .xpath(".//*[@id='BlogArchive1_ArchiveList']"));
widget.click();
findElements() :
Find all elements within the current page using the given "locating mechanism".
Returns List of WebElements.
Syntax:
        WebElement ullist = driver.findElement(By.className("posts"));
  List posts = ullist.findElements(By.tagName("li"));
  System.out.println("List of Posts are Below");
  for (int i = 0; i < posts.size(); i++) {
   String post = posts.get(i).findElement(By.tagName("a")).getText();

   System.out.println(post);
  }
74. How to take the screen shots in seelnium2.0?
//store screenshots
 public static void captureScreenShot(String filePath) {
  File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    try {
   FileUtils.copyFile(scrFile, new File(filePath));
  } catch (IOException e) {
   // TODO Auto-generated catch block
e.printStackTrace();
}
}
75. What is the default time for selenium Ide and webdriver?
Default timeout in selenium ide is 30 seconds.
For web driver go to below URL:


76. Write down scenarios which we can't automate?
Barcode Reader, Captcha etc.
77. In TestNG I have some test's  Test1-Test2-Test3-Test4-Test5I want to run my execution order is Test5-Test1-Test3-Test2-Test4.How do you set the execution order can you explain for that?
Use priority parameter in @test annotation or TestNG annotations.
78. Differences between jxl and ApachePOI.
jxl does not support  XLSX files
jxl exerts less load on memory as compared to ApachePOI
jxl doesn't support rich text formatting while ApachePOI does.
jxl has not been maintained properly while ApachePOI is more up to date.
Sample code on Apache POI is easily available as compare to jxl.

79.How to ZIP files in Selenium

 


// Sample Function to make zip of reports
 public static void zip(String filepath){
  try
  {
   File inputFolder=new File('Mention file path her");
   File outputFolder=new File("Reports.zip");
   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputFolder)));
   BufferedInputStream in = null;
   byte[] data  = new byte[1000];
   String files[] = inputFolder.list();
   for (int j=0; j    {
    in = new BufferedInputStream(new FileInputStream
    (inputFolder.getPath() + "/" + files[j]), 1000); 
    out.putNextEntry(new ZipEntry(files[j]));
    int totalcount;
    while((totalcount= in.read(data,0,1000)) != -1)
    {
     out.write(data, 0, totalcount);
    }
    out.closeEntry();
  }
  out.flush();
  out.close();  
}
  catch(Exception e)
  {
  e.printStackTrace();
           return "Fail - " + e.getMessage();
  }
 }
80. What is default port no?
4444

81. If Default port no is busy how to change port no?
We can use any port number which is valid.. First create an object to remote control configuration.
Use 'setPort' method and provide valid port number(4545,5555,5655, etc).. There after attach this
remote control configuration object to selenium server..i.e
RemoteControlConfiguration r= new RemoteControlConfiguration();
r.setPort(4567);
SeleniumServer s= new SeleniumServer(r);

82. Does Selenium support https protocols?
Yes
83. Majorly asked test scenario with framework in Interviews?
Majorly asked are:
·         Login for Gmail scenario
·         Goggle search and finding no of results
·         Downloading a file and save it
·         Checking mails and deleting them
·         Do shopping in flipkart.com

84. Selenium support mobile applications?
No, it is browser automation tool, it only automates Websites opening in mobile browser, and mobile APPs
 can't be automated.

85. What is wraps Driver?
For casting selenium instance to selenium2 (webdriver). wraps driver is used.
For more details.

86. Can you explain Junit Annotation? If there are 1000 test cases. 500 test cases are executed. How  will you execute the rest of the test cases by using annotation?"
The annotations generated with JUnit 4 tests in Selenium are:
 1. @Before public void method() - Will perform the method() before each test. This method
 can prepare the  test
 2. @Test public void method() - Annotation @Test identifies that this method is a test
method.environment,e.g. read input data, initialize the class)
 3. @After public void method() - Test method must start with test@Before - this annotation
 is used for  executing a method before

87. Difference between assert and verify in selenium  web driver.
When an “assert” fails, the test will be aborted. Assert is best used when the
 check value has to pass for  the test to be able to continue to run log in.
Where if a “verify” fails, the test will continue executing and logging the failure.
Verify is best used to  check non critical things. Like the presence of a
 headline element.

88. "I want to find the location of ""b"" in the below  code, how can I find out without using xpath, name,  id, csslocator, index.
a
b
c

    ·
      driver.findElement(By.xpath("//*[contains(text(),'b')]")).click(); or
//div/button[contains(text(),'b']

89. How to do Applet testing using selenium? 
Please see below URLs:

90.  Name 5 different exceptions you had in selenium web driver and mention what instance you got it and how do you resolve it?
WebDriverException
NoAlertPresentException
NoSuchWindowException
NoSuchElementException
TimeoutException
• WebDriverException
 WebDriver Exception comes when we try to perform any action on the non-existing
driver.
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.close();
driver.quit();

• NoAlertPresentException
When we try to perform an action i.e., either accept() or dismiss() which is not required
at a required place; gives us this exception.
try{
driver.switchTo().alert().accept();
}
catch (NoAlertPresentException E){
E.printStackTrace();
}
• NoSuchWindowException
 When we try to switch to an window which is not present gives us this exception:
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().window("Yup_Fail");
driver.close();
In the above snippet, line 3 throws us an exception, as we are trying to switch to an
window that is not present.• NoSuchFrameException
• Similar to Window exception, Frame exception mainly comes during switching between
the frames.
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().frame("F_fail");
driver.close();
In the above snippet, line 3 throws us an exception, as we are trying to switch to an
frame that is not present.
• NoSuchElementException
 This exception is thrown when we WebDriver doesn’t find the web-element in the DOM.
WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.findElement(By.name("fake")).click();
• TimeoutException
 Thrown when a command does not complete in enough time.
All the above exceptions were handled using try catch exceptions.
91. How do you manage the code versions in your project?
Using SVN or other versioning tools 

92. Latest version of Firefox and selenium in market and the version on which you are testing  which you are testing.
FF Latest version till Dec,2013 for windows7,64 bit :26.0.I use FF 25.0.1 (ur ans. may differ)
Selenium web driver latest version till dec,2013- 2.39.0 I use selenium 2.37 see latest at
93. How to know all the methods supported in web driver and its syntax. 
In Org.openqa.selenium package, web driver interface has all the main methods that can
be used in Selenium Web driver

94. How do you create html test report from your test script? 
• I would see below 3 ways:
• Junit: with the help of ANT.
• TestNG: using inbuilt default.html to get the HTML report. Also XLST reports from ANT,
Selenium, TestNG combination.
• Using our own customized reports using XSL jar for converting XML content to HTML.

95. List the browsers, OS supported by the Selenium
Windows Linux Mac
IE Y NA NA
FF Y Y Y
Safari Y N Y
Opera Y Y Y
Chrome Y Y Y
96. Can you explain Selenium Mobile Automation?
97. What mobile devices it may Support?
Selenium Web driver supports all the mobile devices operating on Android, IOS operating Systems
Android – for phones and tablets (devices & emulators)
iOS for phones (devices & emulators) and for tablets (devices & emulators)
98. What is the difference between single and  double slash  in Xpath?
/
1.It starts selection from the document node
2. It Allows you to create 'absolute' path expressions
3. e.g “/html/body/p” matches all the paragraph elements
 //
1. It starts selection matching anywhere in the document
2. It Allows you to create 'relative' path expressions
3. e.g“//p” matches all the paragraph elements
99. What are the test types supported by Selenium?
Selenium supports UI and functional testing. As well it can support performance testing
for reasonable load using selenium grid.

100. In what all case we have to go for  “JavaScript executor”.
Consider FB main page after you login. When u scrolls down, the updates get loaded. To
 handle this activity, there is no selenium command. So you can go for javascript to set
the scroll down value like driver.executeScript("window.scrollBy(0,200)", "");

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...