SeleniumQ A28Jan PDF
SeleniumQ A28Jan PDF
Selenium
1. DESCRIBE FRAM E WORK DESIGN & OV ERALL FL OW DIA GRAM USING IN Y OUR PROJ EC T.
2. HOW TO HA NDLE WINDOWS A UTHENTICA TION P OPUP WITH & WITHOUT USING THIRD PA RTY TOOL .
3. WHAT A RE DIFFERENT TYP ES OF EXC EP TION IN SEL ENIUM W EBD RIV ER?
4. WHAT A RE DIFFERENT TYP ES OF M ETHODS IN SEL ENIUM ?
5. CAN WE ENTER TEXT WITHOUT USING SENDKEYS () IF Y ES, HOW ?
6. WRITE A PROGRA M FOR S TRING REV ERSE. (IMP )
7. WRITE A PROGRA M FOR FIBONACCI.
8. WRITE A PROGRA M TO C H ECK WHETHER A NUMBER IS PRIM E .
9. HOW TO FIND M ORE THA N ONE WEB EL EM ENT IN THE LIST ?
10. WHAT IS THE DIFFERENC E BETWEEN DRIVER.CL OSE() A ND DRIV ER.QUIT C OMMA ND ?
11. DIFFERENC E BETWEEN FI NDEL EM ENT /FINDEL EMENTS ?
12. HOW TO COUNT THE NUM BER OF L INKS IN A P AGE ?
13. DOES JAVA SUPP ORTS M UL TIP LE INHERITA NC E ?
14. DIFFERENC E BETWEEN A S SERT A ND V ERIFY IN SEL ENIUM WEBDRIV ER
15. HOW TO TAKE A SC REEN S HOT USING SELENIUM W EBDRIVER ?
16. HOW WILL Y OU EXEC UTE Y OUR LOGIN SCRIP T USING CHROM E BROWSER FROM Y OUR EDITOR USIN G
SEL ENIUM ?
17. CAN WE USE MUL TIPL E CA TCH IN TRY , HOW ?
18. DIFFERENC E BETWEEN WEBDRIV ER/ FIREFOXD RIV ER ?
19. WHAT IS THE DIFFERENC E BETWEEN “GET” A ND “NAVIGATE” TO OP EN A WEB PA GE IN SEL ENIUM WEB
DRIV ER?
20. HOW CAN WE GET THE FONT SIZE, FONT COL OUR ,FONT TY PE USED FOR A PA RTIC ULA R TEXT ON A WEB
PAGE USING SEL ENIUM WEB DRIV ER ?
21. HOW DO Y OU MA NA GE THE CODE VERSIONS IN Y OUR P ROJ EC T ?
22. HOW DO WE HA NDL E DYNA MIC EL EM ENTS WITHOUT USING X PA TH ?
23. HOW TO HA NDLE A LERTS A ND C ONFIRMA TION BOX ES.
24. HOW TO HA NDLE C OLOURS IN W EBDRIVER ?
25. HOW TO P RESS SHIFT +TAB ?
26. HOW TO TAKE A SC REENSHOT IN SEL ENIUM .
27. IS THERE A WA Y TO CL IC K HIDDEN L INK IN WEBDRIV ER.
28. LOGIN FOR G MAIL SC ENA RIO ?
29. WHAT A RE THE TEC HNICAL C HALL ENGES THA T Y OU FAC ED WITH SELENIUM ?
30. DIFFERENC E BETWEEN FLEX A ND FL ASH APPL ICA TION
31. WHAT CL ASSES EXTENDS WEBDRIV ER
32. WHAT IS AC TION CLA SS IN W EBDRIV ER ?
33. WHAT IS SEL ENSE
34. WHAT IS SIDE
35. WHA T IS THE HIERARCHY OF TESTNG A NNOTA TION
36. WHAT IS SELENIUM ? WHA T A RE THE DIFFERENT SEL ENIUM C OMP ONENTS ?
37. WHAT IS A N XPA TH ?
38. HOW TO REFRESH A P AGE WITHOUT USING C ONTEX T CLICK ?
39. HOW TO HA NDLE A UTOC OM PLETE BOX IN WEB DRIV ER ?
40. DIFFERENC E BETWEEN TH E SELENIUM 1.0 AND SEL ENIUM 2.0 ??
41. H OW TO SWITC H BETWEEN THE WINDOW S ( GETWINDOWHA NDL E A ND GETWINDOWHA NDL ES )
Selenium Page 2
Selenium Interview Questions :
Selenium Page 3
85. HOW TO STORE A VALUE WHIC H IS TEXT BOXES USING W EBDRIV ER ?
86. HOW TO SWITCH BETWEEN THE WINDOWS
87. HOW TO TYP E NEXT IN A NEW LINE INSIDE A TEXT A REA
88. HOW TO WORK WITH DY NAMIC WEBTA BL E
89. HOW TO WORK WITH RAD IO BUTTON IN WEBDRIV ER
90. HOW WE CA N RETRIEV E THE DY NAM ICALLY CHA NGING ADS
91. IF A SEL ENIUM FUNC TION REQUIRES A SC RIP T A RGUM ENT ,WHAT WOUL D THA T A RGUM ENT L OOK LIKE IN A
GENERAL TERM S ?
92. IF T ESTNG I HAV E SOM E TEST’S T EST -1 T EST -2 T EST-3 T EST-4 T EST-5 I WA NT TO RUN MY EXEC U TION
ORDER IS T EST-5 T EST-4 T EST-3 T EST-2 TEST-1 .HOW DO YOU SET THE EXEC UTION ORDER CA N Y OU
EXPLAIN FOR THA T ?
93. LATEST V ERSION OF FIR EFOX AND SEL ENIUM IN MARKET A ND HE VERSION ON WHIC H Y OU A RE TESTING
94. LIST THE BROWSERS, OS SUPP ORTED BY THE SELENIUM
95. PL EASE TELL M E THE DI FFERENC E B/W IMPLICIT WA IT A ND EXPLICIT WA IT
96. PROVIDE DETA IL ABOUT TESTNG TEST OUTPUT FOL DER.
97. SUPP OSE D EV EL OP ER CHA NGED THE EXISTING IM AGE TO NEW IMAGE WITH SAM E X PA TH .I S TEST CA SE
PASS OR FAIL
98. THERE IS A SC ENA RIO W HENEV ER “ASSERT.A SSERTEQUALS ()” FUNC TION FAIL S A UTOMA TICALL Y IT HA S TO
TAKE SC REENSHOT .HOW CAN YOU AC HIEV E THIS
99. WHAT A RE OOPS C ONC EP T
100. WHAT A RE BENEFITS OF USING TESTNG
101. WHAT A RE BROWSER SUPP ORTED BY SELENIUM IDE
102. WHAT A RE DIFFERENT AC CESS SP EC IFIER IN JAVA
103. WHAR A RE THE DIFFEREN T ASSERTIONS OR C HECK POINTS USED IN Y OUR SC RIP T
104. WHAT A RE THE DIFFERENT PA RAM ETERS F OR @ TEST ANNOTA TION
105. WHAT A RE DIFFERENT TYP ES OF DRIV ER IMPL EM ENTA TION
106. WHAT A RE THE FEA TURES OF TESTNG?
107. WHAT A RE THE OPERA TING SY STEM SUPP ORTED BY SEL ENIUM
108. WHAT A RE THE P OSSIBL E SC ENA RIOS WHERE SEL ENIUM FINDING ELEMENT GET FA ILS
109. WHAT IS THE BASIC USE OF FIREFOX P ROFIL ES A ND HOW CA N WE US E THEM USING SEL ENIUM
110. WHAT IS THE DEFAUL T TIM E FOR SEL ENIUM IDE A ND W EBDRIV ER
111. WHAT IS THE DIFFERENC E B/ W GET WINDOW HA NDLE A ND GET WINDOW HA NDL ES
112. WHAT IS DIFFERENC E BETWEEN GET AND NAV IGA TE TO OPEN A WEB PA G E IN SEL ENIUM W EBDRIV ER
113. WHAT IS DIFFERENC E BETWEEN @ BEFOR M ETHOD A ND @ BEFORE CLASS\
114. WHAT IS DIFFERENCE B ETWEEN A BSOLUTE PA TH AND RELA TIV E PA TH
115. WHAT IS DIFFERENC E BETWEEN DRIV ER.CL OSE A ND DRIV ER .Q UIT
116. WHAT IS DIFFERENC E BETWEEN SEL ENIUM RC A ND W EBDRIVER
117. WHAT IS DIFFERENC E BETWEEN SINGLE A ND DOUBL E SL ASH
118. WHAT IS DIFFERENC E B ETWEEN THREA D.SL EEP () A ND SEL ENIUM SETSPEED(“2000”)
119. WHA T IS DIFFERENC E BETWEEN THREAD. SL EEP() A ND SELENIUM .S ETSPEED()
120. WHA T IS M OST C HALL ENGING TEST PROBL EM IN MY CA REER A UTOMA TION
121. WHA T M OBIL E DEVIC ES IT SUPP ORT
122. WHIC H A RE THE DIFFERENT METHODS TO L OC ATE A N EL EMENT
123. WHIC H ONE IS BETTER ONE XP ATH OR C SS
124. WHIC H REPOSITORY Y OU HAV E USED TO STORE THE TEST SC RIP TS
125. WHY WE REFER FIREFOX DRIVER TO THE WEBDRIV ER INHERITANCE
126. WRITE A C ODE TO MA KE USE OF ASSERT IF MY USER NAM E IS INC ORREC T
127. WRITE A JAVA P ROGRAM FOR SWA PPING OF TWO NUM BERS
Selenium Page 4
128. WRITE DOWN SC ENA RIOS WHICH WE CAN’ T A UTOMA TE.
129. DIFFERENC ES BETWEEN S EL ENIUM WEBDRIVER RC , IDE A ND RC ?
130. DO SHOPP ING IN FL IPKA RT ?
131. WHAT DOES DESIRED CAPA BIL ITES DO ?
132. WHAT IS AC TIONS CLA SS IN W EBDRIVER
133. WHAT IS DIFFERENC E BETWEEN OV ERL OAD A ND OV ERRIDE
134. WHAT IS DIFFERENC E BETWEEN W EBDRIV ER A ND L ISTENER A ND TEST NG LISTENER
135. Read particular cell from html table
136. Logic for looping the table, xapth to iterate rows & columns
137. Can we run Group of test cases using TestNG
138. Ans:Yes
139. checking mails and deleting them
140. Code for opening firefox browser
141. Does selenium support https protocols ?
142. Downloading a file and save it?
143. Explain any 3 testNG annotation
144. Google search and finding no of results
145. TestNG- Write sample code to select browser depending on parameter given in testing.xml
146. Parameter annotation, how to add system property for chrome/iedriver.exe for chrome & IE
147. How to check result with expected
148. Assert.assertEquals().
149. implicit wait and explicit wait- WebDriverWait or Thread.sleep()
150. Can we execute java code without main()no, only can compile
151. . oops concept and diff between overloading and overriding
152. Find the top from array list(10 number) using java code
153. check logic for Fibonacci series, even/odd number, top value from 5th number
154. what are the access modifier and difference.public, private, protected, default
155. What is abstract class with example
156. Polymorphism
157. Inheritance
158. Collection-set,list,map
159. Exception-exception,error,assertion
160. Oops-Type casting of object
161. Wrapper classes
Wrapper classes allows us to convert the primitive types into an object type.
Java is not 100% object oriented programming language because of the 8 primitive types.
Then wrapper classes are introduced to give the primitive types an object form. So the
primitive types can also be stored as an object of its respective wrapper class
The 8 primitive types and its wrapper classes are,
byte. - By te
int - Integer
short - Short
long - Long
float - Float
double - Double
char - Character
boolean - Boolean
Selenium Page 5
This is known as Boxing, converting a primitive type into an object.
Now to get that integer value back,
int a=i.intValue();
This operation is known as Unboxing converting the value of a wrapper class object into a
primitive type.
After java 1.5/5 Box ing and Unboxing became automatic. You can directly assign the
primitive as an object of wrapper class.
Integer i=10;
Before java 1.5/5, databases stores only Object class objects so to store a primitive type into
an ArrayList or Vector wrapper classes are used. Primitive types are converted into wrapper
class object through box ing and upcasted to Object type to store in the database.
The significance of wrapper class comes when you want to write a program which will work
with any type of value. To write such a program declare the arguments as Object type since
Object class is extended by all the other class in java Object class type can store any kind of
objects.
Lets take an example, you want to write a program which will work if you pass any kind of
values
public static void printHello(Object a)
{
Sy stem.out.println("Hello");
}
This program will work with all kind of values. Since Object class is the super most class,
Object type variable can accept any objects. the wr apper class comea into picture when you
pass a primitive type value. Imagine you are calling the function with a value 10
printHello(10);
Now the 10 will be boxed and becomes an object of Integer class(wrapper class) since Integer
ex tends Object the method will work fine.
There are many other uses which comes while overriding the build in methods like
compare(), equals() etc because all these functions have Object type as parameters.
162. Constructor-abstract class
163. Fibonacii,String reverse,remove duplicate from array,sort array, find min-max value from array
164. JDBC
165. TestNG-
166. Annotations
167. Listeners
168. Parameterization/Dataprovider
169. Parallel run- threading(XML)
170. Factory
171. how to create testng.xml programitacally
172. Webdriver-
173. Eventfiringwebdriver
174. Capabilities
175. IE issues & resolution-6-7
176. Execptions
177. Class interface eg.
178. Synchronization-waits
179. Frame
180. xpath,css-functions-contains,sibilings,starts-ends with,relative-absolute xpath,nth-child,nth-of-
type
Selenium Page 6
A GIL E QUESTION A ND A NSWERS
Selenium Page 7
Manual Important Question
Difference bwtween Desktop application and Web Based Application
Selenium Page 8
First of all it is required to identify tasks that an application has to accomplish.
Second, a set of necessary input data has to be created.
Third, expected results have to be defined in order one can judge that an application (a
requested feature) works correspondingly.
Fourth, Executes a test.
Finally, Compares expected results with actual results, and decides whether the test has been
passed successfully.
Environment Specifications:
Selenium WebDriver (Supports all major browsers, we use Mozilla, chrome and IE)
Eclipse IDE
Java
TestNG
AutoIT Tool (Used to handle Windows popup for Document Uploads and Downloads.)
JExcel or Apache POI to perform operations with excel like read, write and update the excel sheet
1. Selenium - Selenium is a well know open source testing framework, which is widely used for testing
Web-based applications. It has different components and in that WebDriver has rendered the Selenium
Remote Control obsolete, and is commonly referred to as Selenium 2.0.Selenium WebDriver supports
most of all browsers to run your test cases and many programming languages like C#, Java, Python,
Ruby, .Net, Perl, PHP, etc.. To create and modify your test scripts.
2. Eclipse IDE: Eclipse is an integrated development environment (IDE) for Java. The Eclipse IDE is the
most known product of the Eclipse Open Source project.
3. TestNG - Is a testing framework inspired from JUnit and NUnit. It has extended new functionalities
which made it more powerful and easier than the other testing frameworks. It supports ReportNG
(simple HTML reporting plug-in) and XLST (Graphical / Pictorial reports) plug-ins to customize or extend
the default TestNG reporting style.
4. AutoIT - AutoIT v3 is a freeware BASIC-like scripting language designed for automating the Windows
GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and
window/control manipulation in order to automate tasks which are not possible with selenium.
Properties file – We use properties file to store and retrieve the UI elements of an application or
a website and data set file paths. It contains id of the elements, name, Xpath or Css selector etc.
Excel files – Excel files are used to pass multiple sets of data to the application.
Xml file – Is used to execute the test scripts. Based on the package or classes or Tests mentioned
in the xml file scripts will be executed.
The following figure explains physical structure of files required for Test Automation Framework
Selenium Page 9
1. UI Map / Object Repository-contains all objects
All the basic required folders are created with the sub folders and classes under each folder
Selenium Page 10
The Following explains the structure in detail:-
UI Map is a concept for defining, storing, and serving UI elements of an application or a website. The
UI Map properties file contains a set of ‘key-value’ pairs, where key is an alias of the UI element, and
a value is the locator.
We will create properties file for every single page and capture all the UI elements present on the
page and use it as per needs.
ManageUsers.Properties
ManageDepartments.Properties
ManageLocations.Properties
Example:-
ManageUsers.Properties
Selenium Page 11
Why and How to use UI Map / Object Repository / OR
To perform any action we need locators. Tool will perform any action based on the locators. For
each and every action tool depends on these locators. If the tool does not identify the locators, it
simply throws an error as Locator / Element Not Found or Identified.
In order to make sure the tool executes smoothly, we need to provide accurate unique identifier /
locators.
We need to keep all the locators at one place where we can easily modify the locators / identifies if
there are any UI changes in the application.
If not, it will become difficult to change even one locator, as it will be used at many different places in
test scripts.
It is always better to keep locators in a separate file and at easily accessible location. It should be
defined in such a way if any new person joins in the middle of the project, he/she should be capable
of making changes / adding any new locators to the file.
Selenium Page 12
In the above example, we have created properties file for each function which will store all the
UI elements.
Example: In Manage Users, we will store all the locators’ / UI elements information which can be
used and accessed in “Add Users”, “Edit Users” and “Delete Users” test cases a value is the locator.
Data set stores the data files, Script reads test data from external data sources and executes test
based on it. Data sets increases test coverage by performing testing with various inputs and reduce
the number of overall test scripts needed to implement all the test cases.Click here for more..
A test is considered as a single action or a sequence of actions, that defines whether a specific
feature meets functional requirements. It has multiple test files / packages / class files which will be
executed based on the configurations defined in testng.xml. Click here for more..
Test report/results is a document which contains summary of test activities. After execution is
completed, it is very important to communicate the test results and findings to the project manager
along with the screenshots for failed tests and with that decisions can be made for the release. Click
here for More..
In order to create a test suite and run separate test cases, we need framework which drives the
automation. Here testng.xml can be called as "driver" which drives several test cases automated
using selenium code. Advantage of using TestNG with Selenium is of running multiple test cases
from multiple classes using xml configuration file .Click here for More..
Selenium Page 13
Properties File
In Selenium .properties files are mainly used to store GUI locators / elements, and also global fields like
database configuration details
'.properties' files are mainly used in Java programs to maintain project configuration data, database
config or project settings etc. Each parameter in properties file is stored as a pair of strings, in key and
value format, where each key is on one line. You can easily read properties from some file using object
of type Properties.
Below is a example program which demonstrate to read the data from .properties file using Java.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
Selenium Page 14
driver.get(prop.getProperty("URL"));
driver.findElement(By.id("Email")).sendKeys(prop.getProperty("username"));
driver.findElement(By.id("Passwd")).sendKeys(prop.getProperty( "password"));
driver.findElement(By.id("SignIn")).click();
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
("D:/Dev/ReadData/src/datafile.properties");
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Selenium Page 15
Properties prop = new Properties();
try {
prop.load(fileInput);
} catch (IOException e) {
e.printStackTrace();
}
URL:- http://gmail.com
password:- password123
username:- testuser
The below is the sample properties file that was used for the above tests.
Selenium Page 16
Selenium Page 17
The only thing we need to do is, give the file name and give the extension as '.properties'. (Example:
dataFile.properties)
Selenium Page 18
Question 2: Handle windows authentication popup without using any third party tool .
1. .keyPress()
robot.keyPress(KeyEvent.VK_ESC);
This will press Escape key on keyboard.
2. .keyRelease()
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
This will release the CAPS_LOCK key.
3. .mousePress()
robot.mousePress(InputEvent.BUTTON1_MASK);
This will press Left mouse button.
4. .mouseRelease()
robot.mouseRelease(InputEvent.BUTTON1_MASK);
This will release Left mouse button.
5. .mouseMove()
robot.mouseMove(coordinates.getX(), coordinates.getY());
This will move the mouse pointer to X and Y co-ordinates.
Selenium Page 19
package com.easy.upload;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
/**
* This method will set any parameter string to the system's clipboard.
*/
public static void setClipboardData(String string) {
//StringSelection is a class that can be used for copy and paste
operations.
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception exp) {
exp.printStackTrace();
}
}}
Selenium Page 20
Scenario-
1-Open Firefox and Create profile in monster.com
2- Click on upload button and select the file and save
Lets implement the same
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.*;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
@Test
public void Fileupload() throws AWTException, InterruptedException
{
// Start browser
WebDriver driver = new FirefoxDriver();
// maximize browser
driver.manage().window().maximize();
// Specify the file location with extension
StringSelection sel = new StringSelection("C:\\Users\\Desktop\\1.doc");
// Copy to clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel,null);
System.out.println("selection" +sel);
// Open Monster.com
driver.get("http://my.monsterindia.com/create_account.html");
Thread.sleep(2000);
// This will scroll down the page
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scroll(0,350)");
// Wait for 5 seconds
Thread.sleep(5000);
// This will click on Browse button
driver.findElement(By.id("wordresume")).click();
System.out.println("Browse button clicked");
// Create object of Robot class
Robot robot = new Robot();
Thread.sleep(1000);
// Press Enter
robot.keyPress(KeyEvent.VK_ENTER);
// Release Enter
robot.keyRelease(KeyEvent.VK_ENTER);
// Press CTRL+V
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// Release CTRL+V
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
Thread.sleep(1000);
// Press Enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}}
Selenium Page 21
Question 3 : Different types of exception in selenium Webdriver.(Asked)
https://selenium.googlecode.com/git/docs/api/py/common/selenium.common.exceptions. html
Examples:
class WebDriverException(Exception):
class ErrorInResponseException(WebDriverException):
class InvalidSwitchToTargetException(WebDriverException):
class NoSuchFrameException(InvalidSwitchToTargetException):
class NoSuchWindowException(InvalidSwitchToTargetException):
class NoSuchElementException(WebDriverException):
class NoSuchAttributeException(WebDriverException):
class StaleElementReferenceException(WebDriverException):
class InvalidElementStateException(WebDriverException):
class NoAlertPresentException(WebDriverException):
class ElementNotVisibleException(InvalidElementStateException):
class ElementNotSelectableException(InvalidElementStateException):
class InvalidCookieDomainException(WebDriverException):
class UnableToSetCookieException(WebDriverException):
class RemoteDriverServerException(WebDriverException):
class TimeoutException(WebDriverException):
class MoveTargetOutOfBoundsException(WebDriverException):
class UnexpectedTagNameException(WebDriverException):
class InvalidSelectorException(NoSuchElementException):
class ImeNotAvailableException(WebDriverException):
class ImeActivationFailedException(WebDriverException):
WebDriverException
WebDriver Exception comes when we try to perform any action on the non-
existing driver.
driver.get("http://google.com");
driver.close();
driver.quit();
NoAlertPresentException
Selenium Page 22
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();
E.printStackTrace();
NoSuchWindowException
driver.get("http://google.com");
driver.switchTo().window("Yup_Fail");
driver.close();
NoSuchFrameException
Selenium Page 23
driver.get("http://google.com");
driver.switchTo().frame("F_fail");
driver.close();
NoSuchElementException
driver.get("http://google.com");
driver.findElement(By.name("fake")).click();
TimeoutException
StaleElementException
Most automation tools depend on the concept of the page has finished loading. With AJAX and Web 2.0
this has become a grey area. META tags can refresh the page and Javascript can update the DOM at
regular intervals.
For Selenium this means that StaleElementException can occur. StaleElementException occurs if I find
an element, the DOM gets updated then I try to interact with the element.
Actions like:
driver.findElement(By.id("foo")).click();
are not atomic. Just because it was all entered on one line, the code generated is no different than:
By fooID = By.id("foo");
WebElement foo = driver.findElement(fooID);
foo.click();
If Javascript updates the page between the findElement call and the click call then I'll get a
StaleElementException. It is not uncommon for this to occur on modern web pages. It will not happen
consistently however. The timing has to be just right for this bug to occur.
Selenium Page 24
Generally speaking, if you know the page has Javascript which automatically updates the DOM, you
should assume a StaleElementException will occur. It might not occur when you are writing the test or
running it on your local machine but it will happen. Often it will happen after you have 5000 test cases and
haven't touched this code for over a year. Like most developers, if it worked yesterday and stopped
working today you'll look at what you changed recently and never find this bug.
The method takes as input a locator for the element you want to click. If it is successful it will return true.
Otherwise it returns false. If it makes it past theclick call, it will return true. All other failures will return
false.
Personally, I would argue this should always work. If the developers are refreshing the page too quickly
then it will be overloading the browser on the client machine.
Selenium Page 25
Question 4: Different types of method in Selenium(Asked)
get() close()
getCurrentUrl(); quit()
getTitle() getWindowHandle()
findElements() getWindowHandles()
findElement() navigate()
getPageSource() manage()
Selenium Page 26
Question 7: Write a program for Fibonacci.
Question 9: How to find more than one web element in the list?
At times, we may come across elements of same type like multiple hyperlinks, images etc arranged in an
ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of
code and this can be done using WebElement List.
Sample Code
// Storing the list
List <WebElement> elementList =
driver.findElements(By.xpath("//div[@id='example']//ul//li"));
Selenium Page 27
// Fetching the size of the list
int listSize = elementList.size();
for (int i=0; i<listSize; i++)
{
// Clicking on each service provider link
serviceProviderLinks.get(i).click();
// Navigating back to the previous page that stores link to service providers
driver.navigate().back();
}
Question 10: What is the difference between driver.close() and driver.quit command?
close(): WebDriver’s close() method closes the web browser window that the user is currently working
on or we can also say the window that is being currently accessed by the WebDriver. The command
neither requires any parameter nor does is return any value.
quit(): Unlike close() method, quit() method closes down all the windows that the program has opened.
Same as close() method, the command neither requires any parameter nor does is return any value.
Selenium Page 28
Iterator and advanced for loop can do similar job; However, the inconsistency on page navigation
within a loop can be solved using array concept.
driver.get("www.xyz.com");
WebElement element = driver.findElement(By.id(Value));
List<WebElement> elements = element.findElements(By.tagName("a"));
int sizeOfAllLinks = elements.size();
System.out.println(sizeOfAllLinks);
for(int i=0; i<sizeOfAllLinks ;i++)
{
System.out.println(elements.get(i).getAttribute("href"));
}
for (int index=0; index<sizeOfAllLinks; index++ ) {
getElementWithIndex(By.tagName("a"), index).click();
driver.navigate().back();
}
Selenium Page 29
Java
driver.get(baseUrl + "https://www.google.co.in");
List<WebElement> all_links_webpage = driver.findElements(By.tagName("a"));
System.out.println("Total no of links Available: " + all_links_webpage.size());
int k = all_links_webpage.size();
System.out.println("List of links Available: ");
for(int i=0;i<k;i++)
{
if(all_links_webpage.get(i).getAttribute("href").contains("google"))
{
String link = all_links_webpage.get(i).getAttribute("href");
System.out.println(link);
}
Types of Inheritance:
Multiple inheritance.
Multilevel inheritance.
Multiple inheritance:
The concept of getting the properties from multiple class objects to sub class object with same
priorities is known as multiple inheritance.
Java Doesn't Support multiple Inheritance.
Diamond problem:
In multiple inheritance there is every chance of multiple properties of multiple objects with the
same name available to the sub class object with same priorities leads for the ambiguity.
Selenium Page 30
7. }
8. Class C extends A{
9. public void show(){
10. }
11. }
12. Class D extends B,C{ // not supported by java leads to syntax error.
13. }
Selenium Page 31
4. }
5. interface B{
6. public void display();
7. }
8. Class C Implements A,B{
Here it seems we are achieving multiple inheritance by using interfaces. but we are not.
Syntactically it seems to multiple inheritance but the actual implementation of multiple
inheritance is not there. how can i say that? let me clear
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.
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
@Test
public void openBrowser() throws Exception {
driver = new FirefoxDriver();
Selenium Page 32
driver.manage().window().maximize();
driver.get("http://www.google.com");
try{
//the below statement will throw an exception as the element is not
found, Catch block will get executed and takes the screenshot.
driver.findElement(By.id("testing")).sendKeys("test");
//if we remove the below comment, it will not return exception and
screen shot method will not get executed.
//driver.findElement(By.id("gbqfq")).sendKeys("test");
}
catch (Exception e){
System.out.println("I'm in exception");
//calls the method to take the screenshot.
getscreenshot();
}
}
Question 16:How will you execute your login script using chrome browser from your editor
using selenium?
Download the chromedriver from this
path: http://code.google.com/p/chromedriver/downloads/list and store in the directory
For Chrome browser we need to set the chromedriver path in the editor which is as shown
below:
System.setProperty("webdriver.chrome.driver","C:\\Users\\Public\\Documents\\S
elenium\\chromedriver.exe");
Selenium Page 33
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e)
{System.out.println("common task completed");}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Question 19: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.Forexample 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
Question 20:How can we get the font size, font colour ,font type used for a particular
text on a web page using selenium web driver ?
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size);
Selenium Page 34
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-colour);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-type);
driver.findelement(By.Xpath("Xpath ").getcssvalue("background-colour);
1. Absolute Xpath
Xpath Position or Absolute Xpath are most frequently used to resolve the dynamic element issues. Only
problem with using XPath locators is that they are very fragile. They are most prone to breakage in case
of change in web page. This factor could get worse exponentially as the test suite size and complexity
increases. Below is an example of Absolute XPath and XPath Position
web_element_name=html/body/div[30]/div[2]/div[2]/div/div/div/div[1]/table/tbody/tr/td[2]/table/tbo
dy/tr/td[1]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]/em/button
//p[6]/label[2]/div/ins
2.Identify Element by starting Text
If the dynamic elements have a definite pattern to them, then we can also use JavaScript functions like
“starts-with” or “contains” in our element locators to separate the dynamic part of locator from static
part.
Selenium Page 35
For example, in case of dynamic submit button Id example which we discussed earlier, we can apply
‘starts-with’ function to access this locator irrespective of its dynamic part.
XPath: //button[starts-with(@id, 'Submit-')]
Similarly, in some scenarios where dynamic element is surrounded by a static value, we can use
‘contains’ function. For example we have following element locators…
<input class="new-userfield-001">
<input class="old-userfield-002">
As we can see ‘usefield’ part of element is static, so we can apply ‘contains’ function to access this
element locator as shown below…
XPath: //input[contains(@class, 'suggest')].
4. Identify Element by Index
If there are multiple elements present on page with same locator then we can use following Java code in
our selenium WebDriver script to interact with element of particular index.
driver.findElements(By.xpath(“//*submit”)).get(0).click();
5. Identify Element with reference of a closest stable element
We can use the DOM structure to find the closest stable element first and then this stable element can
be used as a reference element to find the required element.
XPATH: //span1/../following-sibling::div//button1
DOM structure could be found using Firefox extension like Firebug and FirePath. But in complex and
large applications this approach is difficult to use because of large DOM structure.
For web elements like text field and text areas we can identify them by using the stable text labels
nearby. This approach might not be possible in all scenarios but it does resolve the dynamic element
issues where possible. Example of this approach is shown below.
//label1/following::input
Alert alert()
The preceding method will switch to the currently active modal dialog on the web page. This
returns an Alert instance where appropriate actions can be taken on that dialog. If there is no dialog
currently present, and you invoke this API, it throws back a NoAlertPresentException.
The Alert interface contains a number of APIs to execute different actions. The following list
discusses them one after the other:
Selenium Page 36
void accept(): This is equivalent to the OK button action on the dialog. The corresponding OK button
actions are invoked when the accept() action is taken on a dialog.
void dismiss():This is equivalent to clicking on the CANCEL action button.
java.lang.S tring getText(): This will return the text that appears on the dialog. This can be used if you
want to evaluate the text on the modal dialog.
void sendKeys(java.lang.S tring keysToSend) : This will allow the developer to type in some text into the
alert if the alert has some provision for it.
Selenium Page 37
Question 26:How to take a screenshot in selenium.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
document.getElementsByClassName('post-tag')[0].click();
The above javascript would click on the "Selenium" tag on the top right of this page (next to
your question), even if it were hidden.
All you need to do is issue this JS instruction via the JavascriptExecutor interface like so:
(JavascriptExecutor(webdriver)).executeScript("document.getElementsByClassName('post-
tag')[0].click();");
Selenium Page 38
//Click on Compose Mail.
driver.findElement(By.xpath("//div[
icon present in the top right navigational Bar
driver.findElement(By.xpath("//div[@class='gb_1 gb_3a gb_nc gb_e']/div/a")).click();
//Click on 'Logout' Button@class='z0']/div")).click();
// Click on the image
driver.findElement(By.xpath("//*[@id='gb_71']")).click();
//Close the browser.
driver.close();
}
}
Question 29:What are the technical challenges that you faced with selenium?
There are quite a few technical challenges we faced in the initial stages of implementation; as
my insurance application has a restriction - it opens only in Internet Explorer. With this said,
locating the UI elements (test objects) via., developer tools & view source which was really
challenging.
Also there are many of the objects which doesn’t have the id, name; also the application is
mostly in form tables, so we had to go for Xpath-Relative using developer tools post that we
found an Fire-IEBrowser1.4 (VB Scripted excel) that helped in getting the Xpath-absolute &
relative very easily.
We had many obstacles in locating few UI Elements, for which we have used AUI.
It took almost 20 working days to sort out all the issue and finish an end to end business
transaction; with all the solutions found to the major problems we had automated all the 21 live
stream products within a short span of time.
Also mention about other challenges in action builder, selenium crashes, non-support to
window handles, file uploads, IDE to webdriver conversion challenges etc
There is not big difference between the flex and flash. Flash is more oriented or specially designed
software for designer because they can create anything without using any code. Coding is the
advantage for the designer to save his time but he can also perform the same work without coding.
Flash provides number of tools for drawing to create graphics or timeline method for changing those
graphics according to the requirement. Flash is used to create web ads, banner for websites, banner
for social messages, games, and so on. Using Action Script in the flash we can make our design more
lively or realistic. The biggest disadvantage of flash is you have to spend countless hours for creating
attractive framework for your project or website. It is really a time consuming process.
Selenium Page 39
Where as flex is more oriented or created to keep in mind the developers. It has includes almost
every feature of web development. Developers who have good knowledge of html, css and
javascript or little bit designing knowledge can easily understand the flex. You can create graphics by
using inbuilt components or functions. The prime function of php is to create business type
applications. If you want create complex application in other software it will take number of hours
to complete but flex provides the framework applications which includes inbuilt components to
design or develop complex application and with the use of components you will save your time. You
can use several languages in one application like mxml which is similar to html, action script or php,
dotnet and so on. Flex compiles these languages in one SWF file. The only disadvantage of flex is
that it doesn't provide any tool for designing but with the use of stylesheet, properties or
components we can develop or design attractive design for our applications.
Interface WebDriver
All Superinterfaces:
SearchContext
Selenium Page 40
Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its
record and playback feature makes it exceptionally easy to learn with minimal
acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.
Interface Hierarchy
o org.testng.annotations.IAnnotation
o org.testng.annotations.IDataProviderAnnotation
o org.testng.annotations.IExpectedExceptionsAnnotation
o org.testng.annotations.IObjectFactoryAnnotation
o org.testng.annotations.IParameterizable
o org.testng.annotations.IFactoryAnnotation (also extends
org.testng.internal.annotations.IDataProvidable)
o org.testng.annotations.ITestOrConfiguration
o org.testng.annotations.IConfigurationAnnotation
o org.testng.annotations.ITestAnnotation (also extends
org.testng.internal.annotations.IDataProvidable)
org.testng.annotations.IParametersAnnotation
o org.testng.internal.annotations.IDataProvidable
org.testng.annotations.IFactoryAnnotation (also extends
org.testng.annotations.IParameterizable)
org.testng.annotations.ITestAnnotation (also extends
org.testng.annotations.ITestOrConfiguration)
Selenium Page 41
o org.testng.annotations.BeforeSuite (implements java.lang.annotation.Annotation)
o org.testng.annotations.BeforeClass (implements java.lang.annotation.Annotation)
o org.testng.annotations.Factory (implements java.lang.annotation.Annotation)
o org.testng.annotations.Configuration (implements java.lang.annotation.Annotation)
o org.testng.annotations.ObjectFactory (implements java.lang.annotation.Annotation)
Selenium is not just a single tool or a utility, rather a package of several testing tools and
for the same reason it is referred to as a Suite. Each of these tools is designed to cater
different testing and test environment requirements.
Selenium Page 42
Question 38:How to refresh a page without using context click?
Selenium Page 43
Browsers Support | IE, FF(for running), Chrome, Android, iOS | IE, FF, Safari, Opera, Chrome,
Android, IOS
Supporting App's | WebApp's, SAP, Activex, Windows, Siebel | Only Web Applications, Flex
Supporting OS | Windows | Windows, Linux, Mac
QTP allows storing of objects using OR and Se works in descriptive mode only as of today.
Se does not support the window dialog boxes as it can work only in web.
Se supports the largest number of browsers and multiple OS whereas QTP doesn’t
Selenium support wide programming languages whereas QTP supports Vbscript only.
QC-QTP integration allows easier management; Se can integrate with Jira, others
Selenium Page 44
switchTo
WebDriver. TargetLocator switchTo()
The next future commands will be performed to a different frame or window.
Returns: A Target Locator which can be used to switch or select a frame or window
Selenium Page 45
Question 42:Write a code for number of character in string ?
Selenium Page 46
String s = "Count, the number,, of commas.";
int numberOfCommas = s.replaceAll("[^,]","").length();
Implementation 2[edit]
public int count(String input, String countString){
return input.split("\\Q"+countString+"\\E", -1).length - 1;
}
Implementation 3[edit]
public int count(String sourceString, char lookFor) {
if (sourceString == null) {
return -1;
}
int count = 0;
for (int i = 0; i < sourceString.length(); i++) {
final char c = sourceString.charAt(i);
if (c == lookFor) {
count++;
}
}
return count;
}
Implementation 4[edit]
public static int count(String word, Character ch)
{
int pos = word.indexOf(ch);
return pos == -1 ? 0 : 1 + count(word.substring(pos+1),ch);
}
Selenium Page 47
for(WebElement tdElement : td_collection)
{
System.out.println("row # "+row_num+", col # "+col_num+
"text="+tdElement.getText());
col_num++;
}
row_num++;
}
}
}
There are 5 steps to connect any java application with the database in java using JDBC. They are as
follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
In this example, system is the username and oracle is the password of the Oracle database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
Selenium Page 48
}catch(Exception e){ System.out.println(e);}
}
}
In Selenium to work with iFrames, we have different ways to handle frame depending on the
need. Please look at the below ways of handling frames
driver.switchTo().frame(int arg0);
Select a frame by its (zero-based) index. That is, if a page has multiple frames (more than
1), the first frame would be at index "0", the second at index "1" and so on.
Once the frame is selected or navigated , all subsequent calls on the WebDriver interface
are made to that frame. i.e the driver focus will be now on the frame. What ever operations
we try to perform on pages will not work and throws element not found as we navigated /
switched to Frame.
Parameters: Index - (zero-based) index
Returns: driver focused on the given frame (current frame)
Throws: NoSuchFrameException - If the frame is not found.
Selenium Page 49
System.out.println("Navigated to frame with id " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame
+ e.getStackTrace());
}
}
driver.switchTo().frame(String arg0);
Select a frame by its name or ID. Frames located by matching name attributes are always given
precedence over those matched by ID.
Parameters: name Or Id - the name of the frame or the id of the frame element.
Returns: driver focused on the given frame (current frame)
Throws: NoSuchFrameException - If the frame is not found
}
driver.switchTo().frame(WebElement frameElement);
Selenium Page 50
try {
if (isElementPresent(frameElement)) {
driver.switchTo().frame(frameElement);
System.out.println("Navigated to frame with element "+
frameElement);
} else {
}
After working with the frames, main important is to come back to the web page. if we don't switch
back to the default page, driver will throw an exception. Below is the code snippet to switch back to
the default content.
Selenium Page 51
public void switchtoDefaultFrame() {
try {
driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame");
} catch (Exception e) {
System.out
When we perform any action on Ajax controls, using Wait commands will not work as the page is not
actually refreshed here. Pausing the test execution using threads for a certain period of time is also
not a good approach as web element might appear later or earlier than the stipulated period of time
depending on the system’s responsiveness, load or other uncontrolled factors of the moment, leads
to test failures.
The best approach would be to wait for the required element in a dynamic period and then continue
the test execution as soon as the element is found/ visible.
Selenium Page 52
This can done achieved with WebDriverWait in combination with ExpectedCondition , the best way
to wait for an element dynamically, checking for the condition every second and continuing to the
next command in the script as soon as the condition is met.
The below are the few which we use regularly when testing an application : -
Syntax:
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
The above statement will check for the element presence on the DOM of a page. This does not
necessarily mean that the element is visible.
Syntax:
Some times we may also need to check if the element is invisible or not. To do this we need use the
below :
Syntax:
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
Some times you will get an exception as ""org.openqa.selenium.WebDriverException: Element is not
clickable at point (611, 419). Other element would receive the click:'. The below one is used to wait
for the element to be clickable.
Syntax:
Below is the example program to handle Ajax controls with Wait statements. Based on the
application loading time, we can increase or decrease the wait time.
package com.pack.ajax;
import org.openqa.selenium.By;
Selenium Page 53
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
WebDriver driver;
WebDriverWait wait;
@BeforeClass
public void setUp() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to(URL);
}
@Test
public void test_AjaxExample() {
Selenium Page 54
/*Wait for loader to disappear */
By loader = By.className("raDiv");
wait.until(ExpectedConditions.invisibilityOfElementLocated(loader));
WebElement selectedDatesTextElement =
driver.findElement(By.xpath("//div[@class='RadAjaxPanel']/span"));
wait.until(ExpectedConditions.visibilityOf(selectedDatesTextElement));
String textAfterAjaxCall = selectedDatesTextElement.getText().trim();
/*Verify both texts before ajax call and after ajax call text.*/
Assert.assertNotEquals(textBeforeAjaxCall, textAfterAjaxCall);
}
Question 48:Difference Between Interface and Abstract Class
Abstract classes can have constants, members, method stubs (methods without a
body) and defined methods, whereas interfaces can only have constants and methods
stubs.
Methods and members of an abstract class can be defined with any visibility, whereas
all methods of an interface must be defined as public (they are defined public by
default).
When inheriting an abstract class, a concrete child class must define the abstract
methods, whereas an an abstract class can extend another abstract class and abstract
methods from the parent class don't have to be defined.
Similarly, an interface extending another interface is not responsible for implementing
methodsfrom the parent interface. This is because interfaces cannot define any
implementation.
A child class can only extend a single class (abstract or concrete), whereas an
interface can extend or a class can implement multiple other interfaces.
A child class can define abstract methods with the same or less restrictive visibility,
whereas a class implementing an interface must define the methods with the exact
same visibility (public)
Find adds( from Times Of India only) on Google news page
Selenium Page 55
=>Use of xpath functions or 1 value is changing dynamically in xpath & handle it in for loop,
findElements syntax, looping
Given 2 java classes. In one class there are 5-6 method. From class 2 call all methods defined in class1
one by one
Ask not to create object of class1. Without creating object call the methods. [Java reflection]
There is sticky header on page & element hides behind that header on page scroll. Click on such
element
=>Syntax of java script executor, Page scrolling by finding X,Y co-ordinates
There is drop down & depending on drop down selection value in text box is loading(ajax loading).
Verify selection in both fields are correct. .(Asked)
=>Check code for synchronization (Explicit wait) code & logic to compare both values
Question 49:Read excel & fill application form. Click submit & verify success page. Take
screen shot on failure.(Asked)
Code for Excel(POI) api to read excel, code for assertions, TakeScreenshot syntax
HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS ) format files. It
can read files written by Excel 97 onwards; this file format is known as the BIFF 8 format. As the
Excel file format is complex and contains a number of tricky characteristics, some of the more
advanced features cannot be read.
XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLS X) format files.
Similar feature set to HSSF, but for Office Open XML files
try {
// Specify the path of file
File src=new File("filepath/excelsheetname.xlsx");
// load file
FileInputStream fis=new FileInputStream(src);
// Load workbook
XSSFWorkbook wb=new XSSFWorkbook(fis);
Selenium Page 56
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
} catch (Exception e) {
System.out.println(e.getMessage());
try {
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
sh1.getRow(0).createCell(2).setCellValue("2.41.0");
sh1.getRow(1).createCell(2).setCellValue("2.5");
sh1.getRow(2).createCell(2).setCellValue("2.39");
wb.write(fout);
Selenium Page 57
fout.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}}}
Double click on element after which application opens 2 Windows. Perform this scenario & then enter
value in 2nd window.
Action class code to double click & getWindowHandles code
Syntax to add browser capability. Code to set security zones at same level in IE
Code to add capability, capability name to set security zone
Instead of that we can ask testNG to execute the failed test cases again for X (we can define) number of times
and check for the updated results.
To achieve this we need to implement TestNG IRetryAnalyzer. Below is the simple code snippet:
package com.pack.test;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
// Below method returns 'true' if the test method has to be retried else 'false'
//and it takes the 'Result' as parameter of the test method that just ran
public boolean retry(ITestResult result) {
Selenium Page 58
+ getResultStatusName(result.getStatus()) + " for the " + (retryCount+1) + "
time(s).");
retryCount++;
return true;
}
return false;
}
if(status==1)
resultName = "SUCCESS";
if(status==2)
resultName = "FAILURE";
if(status==3)
resultName = "SKIP";
return resultName;
}
}
Create an other class 'RetryListener' by implementing 'IAnnotationTransformer'. We need to setRetryAnalyzer
for iTestAnnotation. In the example below, add the above class name.
package com.pack.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
@Override
public void transform(ITestAnnotation testannotation, Class testClass,
if (retry == null) {
testannotation.setRetryAnalyzer(Retry.class);
}
Selenium Page 59
}
Let us see the example by executing simple tests below. In the below test verifyForgotPasswordPage, We are
trying to verify the wrong text which will return False and the Test fails.
Now the second test will be executed for the value that we defined for 'm axRetryCount' in Retry Class.
package com.pack.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@BeforeClass
public void setup() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
@Test(priority=1)
public void verifyLoginPageText() {
driver.navigate().to(baseURL);
@Test(priority=2)
public void verifyForgotPasswordPage() {
driver.navigate().to(baseURL);
System.out.println("Verify Forgot password page test started");
Selenium Page 60
Assert.assertEquals(pageText, "Wrong text");
//Assert.assertEquals(pageText, "Change your password");
}
}
After executing the above program, We need to add the Listener to testng.xml file. Below is syntax to add
listener for RetryListener.
<listeners>
<listener class-name="com.pack.test.RetryListener"/>
</listeners>
After executing the above program, the output should look like below. The verifyForgotPasswordPage test will
be executed for two times as we have defined 'm axRetryCount = 1', hence when the test fails, it will execute
again for one time. Now the total count of tests it will show as 3, Failures 2. But actually we have only two tests.
To handle this we need to adjust the count by implementing 'ITestListener' and update the count from 'onFinish'
method.
[TestNG] Running:
D:\Selenium\TestNgSample\testng.xml
===============================================
Parallel test runs
Selenium Page 61
14
15
16 //img[@alt=’sometext’]
And so on.
Selenium Page 62
And so on.
And so on.
Selenium Page 63
Using starts-with method
1 //tagname[starts-with(@attribute-name,’’)]
2
3
4
5 //id[starts-with(@id,’’)]
6
7 //a[starts-with(@href=’’)]
8
9 //img[starts-with(@src=’’)]
10
11 //div[starts-with(@id=’’)]
12
13 //input[starts-with(@id=’’)]
14
15 //button[starts-with(@id,’’)]
16
17 And so on.
Selenium Page 64
Using Following node
1 Xpath/following::again-ur-regular-path
2
3 //input[@id=’’]/following::input[1]
4
5 //a[@href=’’]/following::a[1]
6
7 //img[@src=’’]/following::img[1]
Selenium Page 65
1 Xpath/preceding::again-ur-regular-path
2
3 //input[@id=’’]/ preceding::input[1]
4
5 //a[@href=’’]/ preceding::a[1]
6
7 //img[@src=’’]/ preceding::im g[1]
Selenium Page 66
Relative and Absolute XPath method
1 //parent-xpath/absolute xpath
2
3 //input[@id=’section’]/div/input
In testNG we can achieve parallel execution by two ways. One with testng.xml file and we can
Configure an independent test method to run in multiple threads.
First let us look at basic example for Parallel Execution of Test Methods using testng.xml.
We will create a class with Two test methods and try to execute in different threads.
package com.parallel;
import org.testng.annotations.Test;
Selenium Page 67
@Test
public void testCaseOne() {
//Printing Id of the thread on using which test method got executed
System.out.println("Test Case One with Thread Id:- "
+ Thread.currentThread().getId());
}
@Test
public void testCaseTwo() {
////Printing Id of the thread on using which test method got executed
System.out.println("Test Case two with Thread Id:- "
+ Thread.currentThread().getId());
}
}
The below is the simple testng.xml file, if you observe, we are defining two attributes 'parallel' and
'thread-count' at suite level. As we want test methods to be executed in parallel, we have provided
'methods'. And 'thread-count' attribute is to used to pass the number of maximum threads to be
created.
Selenium Page 68
The above result shows that two methods executed using different threads. When we run the same
testng.xml again, the result may vary. The assigning of the thread is take care by the processor. So
we can't say which thread is going to execute which method.
If say example, now there is an other test method which is added in the class.
Now if we execute the same testng.xml, we will get the output as below:
Here Two threads are created. Which ever thread completes the execution of one method, will pick
and execute the other test method.
Let us look at basic example for Parallel Execution of Classes using testng.xml.
We will create a Two classes with Two test methods each and t ry to execute in different threads.
package com.parallel;
import org.testng.annotations.Test;
@Test
public void testCaseOne() {
// Printing class name and Id of the thread on using which test method got
executed
Selenium Page 69
System.out.println("Test Case One in " + getClass().getSimpleName()
+ " with Thread Id:- " + Thread.currentThread().getId());
}
@Test
public void testCaseTwo() {
//Printing class name and Id of the thread on using which test method got
executed
System.out.println("Test Case two in " + getClass().getSimpleName()
+ " with Thread Id:- " + Thread.currentThread().getId());
}
}
Create class and name it as : TestParallelClassTwo.java
package com.parallel;
import org.testng.annotations.Test;
@Test
public void testCaseOne() {
//Printing class name and Id of the thread on using which test method got
executed
System.out.println("Test Case One in " + getClass().getSimpleName()
+ " with Thread Id:- " + Thread.currentThread().getId());
}
@Test
public void testCaseTwo() {
//Printing class name and Id of the thread on using which test method got
executed
System.out.println("Test Case Two in " + getClass().getSimpleName()
+ " with Thread Id:- " + Thread.currentThread().getId());
}
}
The below is the testng.xml file
Selenium Page 70
<test name="Test 1">
<classes>
<class name="com.parallel.TestParallelClassOne"/>
<class name="com.parallel.TestParallelClassTwo"/>
</classes>
</test>
</suite>
In the above testng.xml file, we have defined two attributes 'parallel' and 'thread-count ' at suite level.
As we want classes to be executed in parallel, we have provided 'parallel="classes''. And 'thread-
count' attribute is to used to pass the number of maximum threads to be created.
Now run the above example and see the output, it should look like below :
The above result shows that two classes executed using different threads. When we run the same
testng.xml again, the result may vary. As The thread scheduler dispatches the various threads on
the available processors, and each thread gets some processor time, each in his turn. But the
processor, the order and the time assigned to each thread is up to the OS thread scheduler, and we
does not guarantee the order of execution
Below is the sample test which will only run one browser at a time.
package com.pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
Selenium Page 71
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
@Parameters({ "browser" })
@BeforeTest
public void openBrowser(String browser) {
try {
if (browser.equalsIgnoreCase( "Firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
"D:/Dev/Jars/chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty("webdriver.ie.driver" ,
"D:/Dev/Jars/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
} catch (WebDriverException e) {
System.out.println(e.getMessage());
}
@Test
public void login_TestCase() {
driver.navigate().to(baseURL);
//do something
Selenium Page 72
}
@Test
public void search_TestCase() {
driver.navigate().to(baseURL);
//do something
}
@AfterTest
public void closeBrowser () {
driver.quit();
}
}
In the above code, we have OpenBrowser method with BeforeTest annotation along with parameter
'browser'. In the xml we will define three tests tags to run each test with different browser. We will
compare the browser value with the parameter value and based on that we will create the driver
instance. We have now defined three tests with three browsers (Firefox, Google Chrome and
Internet Explorer)
Below is the testng.xml file which will run all the tests which are defined. We are passing parameter
value with browser name for each test. Tests will be executed in there browsers one by one.
Selenium Page 73
<class name="com.pack.ParallelTest"/>
</classes>
</test>
</suite>
We can also use TestNG to execute tests Simultaneously by defining the"parallel" attribute to "tests"
to run all the tests in defined browser with the help of testng.xml configuration file.
You can find more details about Executing multiple tests using testng
</suite>
After executing you can view the report, which will look like below:
Selenium Page 74
Question 55:Find out broken links on website using selenium webdriver and HTTP Client
Earlier we have seen working with finding broken images, now here we will see finding invalid URLs.
Here a valid URL will always have a status with 200. We have different HTTP status codes which are
used for different purposes. You can check Wiki page for more information on HTTP Status Codes
Here 2xx class of status codes indicates that the action request by client was received and
processed successfully without any issues.
And 4xx class of status code is mainly intended for cases in which the client seems to have erred.
And 5xx class of status codes are intended for cases in which the server seems to have erred.
By just seeing the Links in the UI, we may not be able to confirm if that link is working or not until we
click and verify it.
To achieve this, we can use HTTPClient library to check status codes of the URLs on a page. You
need to download and add it to the build path.
If request was NOT processed correctly, then the HTTP status codes may return any of the above
listed codes but not a 200 status code. We can easily say whether the link is broken or not with
status codes.
Selenium Page 75
Now let us jump into the example, First we will try to find all anchor tags on the page by using
Webdriver. By using the below syntax:
package com.linked;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@BeforeClass
public void setUp() {
@Test
public void validateInvalidLinks() {
try {
Selenium Page 76
invalidLinksCount = 0;
List<WebElement> anchorTagsList = driver.findElements(By
.tagName("a"));
System.out.println("Total no. of links are "
+ anchorTagsList.size());
for (WebElement anchorTagElement : anchorTagsList) {
if (anchorTagElement != null) {
String url =
anchorTagElement.getAttribute("href");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
@AfterClass
public void tearDown() {
if (driver != null)
driver.quit();
}
Selenium Page 77
// verifying response code and The HttpStatus should be 200 if
not,
// increment invalid link count
To achieve this, we can use HTTPClient library to check status codes of the images on a page. If
they don't load correctly, then it will be registered with likely a 404 but not a 200 status code. We can
easily say whether the link is broken or not with status codes.
You can download Apache HTTP Client from here and add to you build path.
First we will try to find all images on the page by using Webdriver. Below is the syntax:
response.getStatusLine().getStatusCode()
Selenium Page 78
Let us look into the example :
package com.linked;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@BeforeClass
public void setUp() {
driver = new FirefoxDriver();
driver.get("http://google.com");
}
@Test
public void validateInvalidImages() {
try {
invalidImageCount = 0;
List<WebElement> imagesList =
driver.findElements(By.tagName("img"));
System.out.println("Total no. of images are " +
imagesList.size());
for (WebElement imgElement : imagesList) {
if (imgElement != null) {
verifyimageActive(imgElement);
Selenium Page 79
}
}
System.out.println("Total no. of invalid images are " +
invalidImageCount);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
@AfterClass
public void tearDown() {
if (driver != null)
driver.quit();
}
Selenium Page 80
Question 58:Page Object Model | POM
Creating Selenium test cases can result in an unmaintainable project. One of the reasons is that too
many duplicated code is used. Duplicated code could be caused by duplicated functionality and this
will result in duplicated usage of locators. The disadvantage of duplicated code is that the project is
less maintainable. If some locator will change, you have to walk through the whole test code to
adjust locators where necessary. By using the page object model we can make non -brittle test code
and reduce or eliminate duplicate test code. Beside of that it improves the readability and allows us
to create interactive documentation. Last but not least, we can create tests with less keystroke. An
implementation of the page object model can be achieved by separating the abstraction of the test
object and the test scripts.
Note: We will follow the same example which we have used in First Test Case. Let’s assume it our
base test case and implement the Page Object Model (POM) in it.
How to do it…
1. Create a ‘New Package‘ file and name it as ‘pageObjects’, by right click on the Project and
select New > Package. We will be creating different packages for Page Objects, Utilities, Test Data,
Test Cases and Modular actions. It is always recommended to use this structure, as it is easy to
understand, easy to use and easy to maintain.
2. Create a ‘New Class‘ file and refer the name to the actual page from the test object, by right click
on the above created Package and select New > Class. In our case it
is Home Page and LogIn Page.
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
element = driver.findElement(By.id("account"));
return element;
element = driver.findElement(By.id("account_logout"));
Selenium Page 81
return element;
}
3. Now create a Static Method for each Element (Object) in the Home Page. Each method will have
anArgument (driver) and a Return value (element).
Driver is being passed as an Argument so that Selenium is able to locate the element on the
browser (driver).
Element is returned, so that an Action can be performed on it.
Method is declared as Public Static, so that it can be called in any other method
without instantiatethe class.
Follow the same rule for creating LogIn Page class.
package pageObjects;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
element = driver.findElement(By.id("log"));
return element;
element = driver.findElement(By.id("pwd"));
return element;
element = driver.findElement(By.id("login"));
return element;
Selenium Page 82
4) Create a ‘New Class‘ and name it as POM_TC by right click on the ‘automationFramework‘
Package and select New > Class. We will be creating all our test cases under this package.
Now convert your old First Test Case in to the new Page Object Model test case. package
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pageObjects.Home_Page;
import pageObjects.LogIn_Page;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.store.demoqa.com");
Home_Page.lnk_MyAccount(driver).click();
LogIn_Page.txtbx_UserName(driver).sendKeys("testuser_1");
LogIn_Page.txtbx_Password(driver).sendKeys("Test@123");
LogIn_Page.btn_LogIn(driver).click();
Home_Page.lnk_LogOut(driver).click();
driver.quit();
You will notice that once you type Home_Page in your test script and the moment you press dot, all
the methods in the Home Page will display. We can expose methods in order to reduce duplicated
Selenium Page 83
code. We are able to call these method multiple times. This will ensure a better maintainable test
code, because we only have to make adjustments and improvements in one particular place.
To do this, first we need to create a class and then implement TestNG 'ITestListener'. We will have a
method called 'onTestFailure'. We need to add the code to take the screen shot in this method.
Selenium Page 84
Instead of just taking the screen shot, we will get the Test method name and take a screen shot with
test name and place it is destination folder.
package com.pack.listeners;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.pack.sample.TestBase;
Selenium Page 85
}
}
public void onFinish(ITestContext context) {}
}
Before executing the above program, we need to add TestListener class in testng.xml file as below:
<listeners>
<listener class-name="com.pack.listeners.TestListener"/>
</listeners>
In the Next tutorial, we will try to extend the way of taking the screen shot and placing it by creating a
folder with Test Class name and Screens shots of that particular test class as shown in below screen
shot. Click here for example on Take Screenshot and place it in a folder with Test Class name
Selenium Page 86
WebDriver.manage().timeouts()
implicitlyWait
[sourcecode language=”java”]
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
[/sourcecode]
The ImplicitWait will tell the webDriver to poll the DOM for a certain duration when trying to find the
element, this will be useful when certain elements on the webpage will not be available immediately
and needs some time to load.
By default it ill take the value to 0, for the life of the WebDriver object instance through out the test
script.
pageLoadTimeout
[sourcecode language=”java”]
driver.manage().timeouts().pageLoadTimeout(100, SECONDS);
[/sourcecode]
Selenium Page 87
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is
negative, page loads can be indefinite.
setScriptTimeout
[sourcecode language=”java”]
driver.manage().timeouts().setScriptTimeout(100,SECONDS);
[/sourcecode]
Sets the amount of time to wait for an asynchr onous script to finish execution before throwing an error.
If the timeout is negative, then the script will be allowed to run indefinitely.
________________________________________
Support.ui
FluentWait
[sourcecode language=”java”]
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
[/sourcecode]
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the
frequency with which to check the condition. Furthermore, the user may configure the wait to ignore
specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an
element on the page.
ExpectedConditions
[sourcecode language=”java”]
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
[/sourcecode]
Models a condition that might reasonably be expected to eventually evaluate to something that is
neither null nor false.
Examples : Would include determining if a web page has loaded or that an element is visible.
Note that it is expected that ExpectedConditions are idempotent. They will be called in a loop by the
WebDriverWait and any modification of the state of the application under test may have unexpected
side-effects.
WebDriverWait will be used as we used in the Expected conditions code snippet as above.
Selenium Page 88
sleeper is something same as the Thread.sleep() method, but this with an Abstraction around the
thread.sleep() for better testability
1-@Override
public void onFinish(ITestContext arg0) {
}
2- @Override
public void onStart(ITestContext arg0) {
}
3- @Override
public void onTestFailure(ITestResult arg0) {
}
etc..
Scenario-
1 -If testcase is failing then what action should be performed
2- If testcase is skipped then what should be action requested and so far..
Selenium Page 89
Step 1- Create a simple class and implement ITestListener listener
Selenium Page 90
Once you implement all your java program will look like
package testngDemo;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
@Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
Selenium Page 91
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
@Override
public void onTestFailure(ITestResult arg0) {
// TODO Auto-generated method stub
@Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
@Override
public void onTestStart(ITestResult arg0) {
// TODO Auto-generated method stub
@Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
Selenium Page 92
I have written a small test for facebook login and I am failing this testcase forcefully so that we can
check how different events will be fired if testcase pass or fail
Program
package testngDemo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.Test;
@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
Selenium Page 93
@Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
@Override
public void onTestFailure(ITestResult arg0) {
@Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
@Override
public void onTestStart(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("TestCase started====" +arg0.toString());
@Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
Selenium Page 94
System.out.println("Congrates Testcase has been passed===="+ arg0.toString());
Step 3- It not completed yet now we need to modify our xml file that is known
as testng.xml and we have to specify this listener and we have to execute
that xml file only.
<listeners>
<listener class-name="testngDemo.ListenerDemoExample"/>
</listeners>
Selenium Page 95
Step 4- Simple run this testng.xml file and analyze the output
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
Selenium Page 96
or
dropdown.selectByValue("prog");
For example, we can count the number of clicks that we have performed in the script by adding
logic to count clicks after each click 'afterClickOn'. We can also when ever there is an exception
using 'onException'.
Let us now look into example by taking the help of class " EventFiringWebDriver" - which is a
wrapper around an arbitrary WebDriver instance which supports registering of a
WebDriverE ventListener for logging purposes.
Now firstly we have to initialize 'EventFiringWebDriver' by passing webdriver instance and then we
need to register event listener for E ventFiringWebDriver instance.
Selenium Page 97
We also need to provide implementation for the events. We can do this by two ways, which ever is
needed for our project.
One way is by using WebDriverE ventListener Interface If we use this, it will implement all the events
that are supported by Webdriver.
An example for this is shown below, when we use this, it will implement all the events like
'beforeNavigateTo', 'afterNavigateTo', 'beforeClickOn' , 'afterClickOn', 'onException' and more such
events
package com.example;
Do not call any of these methods, instead these methods will be invoked automatically
as an when the action done (click, findBy etc).
*/
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;
Selenium Page 98
+ " before any changes made");
}
Selenium Page 99
public void afterFindBy(By by, WebElement element, WebDriver driver) {
System.out.println("Found Element By : " + by.toString());
}
/*
* non overridden methods of WebListener class
*/
public void beforeScript (String script, WebDriver driver) {
}
And other way is by using Class AbstractWebDriverE ventListener If we use this class we can include
only those events which we are interested.
An example for this is shown below, if you observer we have implemented only 5 events,
'beforeNavigateTo', 'afterNavigateTo', 'beforeClickOn' , 'afterClickOn' and 'onException'
package com.example;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;
}
Now let us try to use in our program. From the above two options, here we will use
'AbstractWebDriverE ventListener' and implement the above 5 methods to understand the example
package com.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@BeforeClass()
public void setUp() {
e_driver.register(eventListener);
e_driver.manage().window().maximize();
e_driver.get(appURL);
}
@Test
public void testEventsONE() {
System.out.println("***** Executing Test ONE ***** ");
e_driver.findElement(By.linkText("Gmail")).click();
String pageHeaderText = e_driver.findElement(By.tagName( "h1")).getText();
Assert.assertTrue(pageHeaderText.equalsIgnoreCase(headerText));
}
@Test
public void testEventsTWO() {
System.out.println("***** Executing Test Two ***** ");
//Entering user name and clicking on next
e_driver.findElement(By.id("Email")).sendKeys("username" );
e_driver.findElement(By.id("next")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
//Entering password and clicking on sign-in
e_driver.findElement(By.id("Passwd")).sendKeys("password");
e_driver.findElement(By.id("signIn")).click();
String pageHeaderText =
e_driver.findElement(By.id("errormsg_0_Passwd")).getText();
Assert.assertTrue(pageHeaderText.equalsIgnoreCase(errMessage));
}
}
In the above example, 'setUp' method has driver.get(appURL) which will trigger 'beforeNavigateTo'
and 'afterNavigateTo' methods and prints the URL. 'testEventsONE' and 'testEventsTWO' test
methods has multiple events which will trigger 'beforeClickOn' and 'afterClickOn' events.
[TestNG] Running:
C:\Users\Easy\AppData\Local\Temp\testng-eclipse-310156716\testng-customsuite.xml
===============================================
Default test
Tests run: 2, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
technical
Lets see ho w easy is the first one.
It uses an analo gy with taxi driving.
Selenium WebDriver drives a bro wser the same way a taxi driver drives a cab.
In taxi driving, there are typically 3 actors:
the client; he tells the taxi driver where he wants to go and how to get there
the taxi driver; he executes the client's requests; the taxi driver sends his own
requests to the car
the car; the car executes the taxi driver's requests
The client gets to the destination through dialogues that happen between the client - taxi
driver and taxi driver - car.
In test automatio n with Selenium WebDriver (and other tools), there are 3 actors as well:
When requirement keeps changing, continuously agile tester should take following
approach
Write generic test plans and test cases, which focuses on the intent of the requirement rather
than its exact details
To understand the scope of change, work closely with the product owners or business analyst
2) List out the pros and cons of exploratory testing (used in Agile) and scripte d testing?
Pros Cons
– Scrum does not prescribe any engineering practices – XP does prescribe engineering practices
To improve the performance, the existing code is modified; this is re -factoring. During re-
factoring the code functionality remains same
6) Explain how you can measure the velocity of the sprint with varying team capacity?
When planning a sprint usually, the velocity of the sprint is measured on the basis of
professional judgement based on historical data. However, the mathematical formula used
to measure the velocity of the sprint are,
first – completed story points X team capac ity: If you measure capacity as a percentage of a
40 hours weeks
Second – completed story points / team capacity: If you measure capacity in man-hours
7) Mention the key difference between sprint backlog and product backlog?
Product backlog: It contains a list of all desired features and is owned by the product owner
Sprint backlog: It is a subset of the product backlog owned by development team and
commits to deliver it in a sprint. It is created in Sprint Planning Meeting
8) In Agile mention what is the difference between the Incremental and Iterative development?
Iterative: Iterative method is a continuous process of software development where the
software development cycles are repeated (Sprint & Releases) till the final product is
achieved.
Release 1: Sprint 1, 2… n
9) Explain what is Spike and Zero sprint in Agile? What is the purpose of it?
Sprint Zero: It is introduced to perform some research before initiating the first sprint.
Usually this sprint is used during the start of the project for activities like setting
development environment, preparing product backlog and so on.
Spikes: Spikes are type of stories that are used for activities like research , exploration,
design and even prototyping. In between sprints, you can take spikes for the work related to
any technical or design issue. Spikes are of two types Technical Spikes and Functional
Spikes.
Test driven development or TDD is also known as test-driven design. In this method,
developer first writes an automated test case which describes new function or improvement
Prototypes and Wireframes are prototypes that are widely used as part of Empirical Design
To track the project progress burnup and burn down, charts ar e used Burnup Chart: It
shows the progress of stories done over time Burndown Chart: It shows how much work
was left to do overtime
Scrum ban is a software development model based on Scrum and Kanban. It is specially
designed for project that requires frequent maintenance, having unexpected user stories
and programming errors. Using these approach, the team’s workflow is guided in a way that
allows minimum completion time for each user story or programming error.
It is used to discuss the difficulty of the story without assigning actual hours. The most
common scale used is a Fibonacci sequence ( 1,2,3,5,8,13,….100) although some teams
use linear scale (1,2,3,4….), Powers of 2 (1,2,4,8……) and cloth size (XS, S ,M,L, XL)
The tracer bullet is a spike with the current architecture, the current set of best practices,
current technology set which results in production quality code. It is not a throw away c ode
but might just be a narrow implementation of the functionality.
18) What are the differences between RUP (Rational Unified Process) and Scrum
methodologies?
RUP SCRUM
– Formal project plan, associated with multiple iterations – No end to end project plan. Each next iteration plan is
is used. determined at the end of the current iteration
– Recommended for long term, large, enterprise level – Recommended for quick enhancements and
projects with medium to high complexity organization that are not dependent on a deadline
The primary testing activities during Agile is automated unit testing and explora tory testing.
Though, depending on project requirements, a tester may execute Functional and Non -
functional tests on the Application Under Test (AUT).
Velocity is a metric that is calculated by addition of all efforts estimates related with user
stories completed in an iteration. It figures out how much work Agile can complete in a
sprint and how much time will it need to finish a project.
22) What are the qualities of a good Agile tester should have?
Scrum Masters: It coordinates most of the inputs and outputs required for an agile program
Development Managers : They hire right people and develop them with the team
24) Mention in detail what are the role’s of Scrum Master?
Re-factoring
Non-solo development
Static and dynamic code analysis
Reviews and Inspection
Iteration/sprint demos
All hands demo
Light weight milestone reviews
Short feedback cycles
Standards and guidelines
26) Mention what are the Tools that can be useful for screenshots while working on Agile
projects?
BugDigger
BugShooting
qTrace
Snagit
Bonfire
Usersnap
27) Mention what are the advantages of maintaining consistent iteration length throughout the
project?
If a timebox plan needs to be reprioritized it should include whole team, product owner, and
developers.
The burn-down chart shows the remaining work to complete before the timebox (iteration)
ends.
Scrum : In the scrum, a sprint is a basic unit of development. Each sprint is followed by a
planning meeting, where the tasks for the sprint are identified and estimated. During each sprint,
the team creates finished portion of a product
Agile: In Agile, each iteration involves a team working through a full software development
cycle, including planning, design, coding, requirement analys is, unit testing, and acceptance
testing when a product is demonstrated to stakeholders
In simple words, Agile is the practice and scrum is the process to following this practice.
31) Mention what are the challenges involved in AGILE software development?
Is functionality split-able
Is customer available
Are requirements flexible
Is it really time constrained
Is team skilled enough
33) Explain how can you implement scrum in an easy way to your project?
These are the tips which can be helpful to implement scrum in your project
At the end of the sprint- hold a sprint review meeting, mention what is achieved or delivered
in the sprint.
A product roadmap is referred for the holistic view of product features that create the
product vision.
Normally a stable and relatively fast internet connection, but that's not a
guarantee, so you need to test how the app handles online and offline states.
Different OSes. If you build a Mac app, how far back are you supporting? Does the
installer prevent installatio n on unsupported OSes?
Different hardware configuratio ns: this can range from having enough RAM, to
enough storage space, to differing screen resolutions. What does the top of the
line hardware config look like? What does the bottom of the line look like?
Software conflicts! This is one of the hardest, and generally where the most
problems/edge cases creep up. Is that obscure firewall that your end user is using
blocking required network access? Is that spyware that's installed and trying to
record all outgoing and incoming packets messing up your app's connection?
Security. If an individual's machine is exploited, does your app store sensitive
information locally in an easily read format? An example of this is I've seen
several Mac Apps that store passwords in either plain text or or an easily decrypt -
able format in a .plist file.
Applications that run 100% within a browser. This is where the waters get muddy, because
there are a group of apps on both the desktop and on mobile that are just web apps,
running within an app-specific browser. An example of one of these would have been the
early versions of the Facebook app -- those were just a bunch of web views running within a
browser window. Sometimes those are hard to identify, but a surefire tell is if your app
updates without you needing to do anything from the App Store/Play Store.
Now that the longest pre-amble I've ever written is complete, let's get on with answering the
question! Web:
External services -- a lot of web apps will rely on external apps and infrastructure.
What happens if (for example) I'm hosting all of my files with S3, and Amazon has
an outage?
Security! Chances are, with a web app, you've got more than one person using the app. How
do you prevent one individual's info from being accessible by others? How do you prevent
your app from being completely compromised and used to infect your users' computers with
virii?
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
SQL
6. What is a primary key?
A primary key is a combination of fields which uniquely specify a row. This is a special kind
of unique key, and it has implicit NOT NULL constraint. It means, Primary key values cannot
be NULL.
A Unique key constraint uniquely identified each record in the database. This provides
uniqueness for the column or set of columns.
A Primary key constraint has automatic unique constraint defined on it. But not, in the case
of Unique Key.
There can be many unique constraint defined per table, but only one Primary key constraint
defined per table.
A foreign key is one table which can be related to the primary key of another table.
Relationship needs to be created between two tables by referencing foreign key with the
primary key of another table.
9. What is a join?
There are various types of join which can be used to retrieve data and it depends on the
relationship between tables.
Inner join.
Inner join return rows when there is at least one match of rows between the tables.
Right Join.
Right join return rows which are common between the tables and all rows of Right hand
side table. Simply, it returns all the rows from the right hand side table even though there
are no matches in the left hand side table.
Left Join.
Left join return rows which are common between the tables and all rows of Left hand side
table. Simply, it returns all the rows from Left hand side table even though there are no
matches in the Right hand side table.
Full Join.
Full join return rows when there are matching rows in any one of the tables. This means, it
returns all the rows from the left hand side table and all the rows from the right hand side
table.
A view is a virtual table which consists of a subset of data contained in a table. Views are
not virtually present, and it takes less space to store. View can have data of one or more
tables combined, and it is depending on the relationship.
A DB query is a code written in order to get the information back from the database. Query
can be designed in such a way that it matched with our expectation of the result set. Simply,
a question to the Database.
A subquery is a query within another query. The outer query is called as main query, and
inner query is called subquery. SubQuery is always executed first, and the result of
subquery is passed on to the main query.
A correlated subquery cannot be considered as independent query, but it can refer the
column in a table listed in the F ROM the list of the main query.
A Non-Correlated sub query can be considered as independent query and the output of
subquery are substituted in the main query.
th th
I am Manas Kumar Jha I was born and bought up in bihar and did my 10 and 12 from
campus public school Pusa Samastipur Bihar that I did my Bachelor of engineering from