0% found this document useful (0 votes)
17 views77 pages

Selenium WebDriver Installation Guide

The document provides a comprehensive guide on Selenium WebDriver, an open-source tool for automating web applications. It includes installation instructions, programming examples in Java, and explanations of various Selenium concepts such as browser navigation, handling web elements, and locators. Additionally, it covers HTML basics and the importance of attributes in identifying web elements for automation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views77 pages

Selenium WebDriver Installation Guide

The document provides a comprehensive guide on Selenium WebDriver, an open-source tool for automating web applications. It includes installation instructions, programming examples in Java, and explanations of various Selenium concepts such as browser navigation, handling web elements, and locators. Additionally, it covers HTML basics and the importance of attributes in identifying web elements for automation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Vinay2ml@gmail.

com

Selenium: Webdriver:

It is a free and open source web application automation tool, which performs the action on the
application by calling native methods of the browser.

Installing selenium web driver: or setup the web driver

1) Required software’s:
2) JDK(Java development kit) latest version 1.7 or 1.8
3) Eclipse IDE
4) Mozilla Firefox browser
5) Selenium jar file

Download the selenium jar file steps:

1) Open browser and click this link :

2) Click download version on selenium server section :


2.43.0 And save into respective location
Vinay2ml@[Link]

3) Open Eclipse create a java project

Select->properties->Java build pathLibraries -> Add external Jar files


And select the selenium jar file and click ok.

Selenium supports following languages:


1) Java
2) C#
3) Python
4) Java script
5) Perl
6) Php

Ex:
package [Link];

import [Link];

publicclass demo {

publicstaticvoid main(String[] args) {


// TODO Auto-generated method stub
FirefoxDriver f =new FirefoxDriver();
[Link]();
}

Advantages:
1) Free :selenium can be used for commercial purpose also without purchasing the
licensee
2) Open source: you can view and download and customize the source code of
selenium itself.
3) Web application: any application which is opened browser and automated using
selenium
4) Ex: [Link], [Link]
Vinay2ml@[Link]

5) Automation tool: it is software application which is used to test another


application automatically
6) Native method: The methods which are available in the browser and which are
exposed by browser developers are called as native methods. Ex : close()
Firefox

Architecture of selenium web driver:

Interface
SearchContext

Web driver
Interface

RemoteWebDriver Class

FirefoxDriver ChromeDriver

Search context: is a super most interface which is extended by


webDriver interface.

RemoteWebdriver: class implements all the abstract methods of the


both interface. The browser specific class such as Firefox,
chrome driver, internet explorer driver, safari driver, extends
Remote webdriver class.

We do browser compatibility testing that is use a browser such as


Firefox, while writing the automation script but will run it on
different browser. In order to do this we will use runtime-
polymorphism concept to achieve this using up casting in
selenium, we always up cast the browser object, web driver
interface as below.

Ex: Webdriver driver = new FirefoxDriver ();


Vinay2ml@[Link]

1) How do you close the browser?


Webdriver driver =new FirefoxDriver ();
[Link]();

2) How do you close the browser without using close() browser ?


WebDriver driver = new FirefoxDriver ();
[Link]()

3) How do you open the web page ?


webDriver driver = new FirefoxDriver();
[Link](‚[Link]
[Link]();

We should specify complete URL of the application starting


from the protocol and get Method make the selenium to wait
till the webpage is completely loaded.

4) How do you open the webpage without using the get method ()?
Webdriver driver = new FirefoxDriver ();
[Link] (‚[Link]
driver. Close ()

5) How do you click on back button in browser web page.

WebDriver driver =new FirefoxDriver();


[Link]("http:\\[Link]");
[Link]().to("http:\\[Link]");
[Link]().to("http:\\[Link]");
[Link]().back();
String utl = [Link]();
if([Link]("bing")){
[Link](utl);
[Link]("Back page %s loaded successfully",utl);
}else{
[Link]("bing page is not loaded");
}
[Link]();

6) How do you click on forward button in browser ?

publicclass pythonfile {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]");
[Link]().to("http:\\[Link]");
[Link]().back();
[Link]().forward();
[Link]();
Vinay2ml@[Link]

}
7) How do you click on forward button in browser web page.

publicclass forwardback {

publicstaticvoid main(String[] args)


{
WebDriver driver =new FirefoxDriver();
[Link]("http:\\[Link]");
[Link]().to("http:\\[Link]");
[Link]().back();
[Link]().forward();
if([Link]().contains("[Link]")){
[Link]("[Link] loaded successfully ");

}else
{
[Link]("[Link] not laoded ");
}
[Link]();
}

}
8) How do you refresh the web page?

publicclass refreshpage {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver() ;
[Link]("[Link]
[Link]().refresh();
[Link]();

9) How do you maximize the web page ?

publicclass maxmizepage {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]().refresh(); //refresh the page
[Link]().window().maximize() ;
[Link]();

}
Vinay2ml@[Link]

10) Write a script open Google in web page and verify that google page is
loaded ?

publicclass gettitilepage {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]");
String title = [Link]();
if([Link]("Google")){
[Link]("Goole title is present");
}else {
[Link]("Google title is not present");
}
[Link]() ;
}

String comparison if case sensitive to handle such scenarios use


Equalignorecase().
If the value keep changing then we can use contains() function.

publicclass gettitilepageignorecase {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]");
if([Link]().equalsIgnoreCase("google")){
[Link]("Google titile present");
}
else{
[Link]("Google title is not present");
}
[Link]();
}

11) Write a code to get the url present in the address bar ?

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]");
String url =[Link]();
[Link](url);
[Link]();

}
Vinay2ml@[Link]

Assignment:
1) Write a script open [Link] verify that is navigated to
[Link]

publicclass geturl {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]");
String url =[Link]();
[Link](url);
if([Link]("[Link]")){
[Link]("[Link] navigated to [Link]
successfully");
}else {
[Link]("[Link] is not navigated to [Link]
");
}
[Link]();

HTML: (hypertext markup Language).


Basically use to develop web pages in selenium, before
performing any action on the elements (button, textboxes,
and links), it is to identify that element uniquely in order
to do this, it uses characteristics of those elements, which
is given by the application developer using HTML.

Characteristics can also be called as attributes or


properties.
HTML is not case sensitive
We can use notepad itself to write the html code but by
saving the code using .html as extension.

Use predefined key words with in angle bracket


<html> these are called html tags.
Use Forward ‘/’ to end the tag ending all the tag is
mandatory </html>

Ex:
<html>
<title>Qspider</title>
<body>
Welcome !
</body>
</html>
Vinay2ml@[Link]

Important Web elements:


1) Toolbox UN: <input type =’text’ value = ‚abc‛>
2) PasswordFiled PW: <input type =‛password‛ value
=‛xyz‛>
3) Checkbox <input type = ‚checkbox‛>
4) Button <input type = ‚button‛ value = ‚ok‛
5) Radiobutton <input type =‛radio‛>
6) Filebrowser <input type =‛file‛>
7) Image <img src =‛[Link]‛>
8) List items <select>
<Option> idly </option>
<Option>vada</option>
<Option>dosa</option>
<Option>pulhogra</option>
</select>
9) Multi select code <select multiple = ‚true‛>
10) Hyper link <a href =‛[Link] title
=‛click here‛>Qspider</a>

Create a table:
<html>
<body>
<table border =‛1‛>
<tbody>
<tr>
<th>snio</th>
<th>subject</th>
<th>Apply</th>
</tr>
<tr>
<td>1</td>
<td>Java</td>
<td>input type =‛checkbox‛></td>
</tr>
</tbody>
</table>
</body>
</html>

Component of web element:

<Html tags>
<html>
<body>
<title>
Vinay2ml@[Link]

<input> , <img>, <select> , <option><a><link>, <br>


<table> , <tbody>, <tr><td><th>, <head>, <script>,
<form> , <span>, <li>, <ol>, <ul><iframe>, <div>

Any pair of words separated by ‚=‛ is called as attribute


also called as, property name and property value.
The attribute will be present after the html tag till ‚<‛
symbol.
Ex:
Type =‛text‛
Value ‚abc‛
Src =‛[Link]‛
Multiple =‛true‛
Tittle =‛checkbox‛
Boder =‛1‛
Id =‛username‛
Class =‛textfiled‛
Name =‛username‛
Placeholder =‛username‛

Any word which is present after the greater than symbol till
the end of respective html tag is called as text of the
element.

<div class =‛lable‛ >Tasks </div> } web element


(div) tag -> gettagname();
Getattribute(property name)
Gettext()

Locator: Selenium identify the element using locators and


there are 8 types of locator are available.

1)tagName - tag
2) id , name, className are called attribute
3) linkText, parstialLinkText, are called Text
4) CssSelector , xpath are called Expression

Note: all the locator are present in ‚By‛ class as static


methods, they take as string as argument and return on
object of type ‚By‛ this object is used in find element.
findElement() and findElemets();
to search element in the webpage, if search is successful
element is found and get return object of type webelement.

Ex:
<html>
Vinay2ml@[Link]

<body>
< a href =‛[Link] id =‛a1‛ name =‛n1‛ class
=‛c1‛>Qspider</a>
</body>
</html>

1)Selenium Script:To click on the link on the sample web


page using ‚tagName()‛ as locator.

publicclass tagNameclick {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("a")).click();
[Link]();
}
}

2)Selenium Script: To click on the link on the sample web


page using attribute ‚id()‚as locator.

publicclass attribute_id {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("a1")).click();
[Link]();
}
}

4) Selenium Script: To click on the link on the sample web page


using attribute ‚className()‛ as locator.
publicclass attribute_class {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("c1")).click();

}
5) Selenium Script: To click on the link on the sample web page
using text property ‚linkText()‛ as locator.
publicclass testfindelement {
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
Vinay2ml@[Link]

[Link]([Link]("Qspider")).click();

}
6) Selenium Script: To click on the link on the sample web page
using text ‚PatrialLinkText() property as locator.

publicclass partiallinktext {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]("[Link]
[Link]([Link]("spider")).click();
[Link]();
}

If specified locator is not matching with any of the element then findElement()
method will throw Exception ‚NoSuchElementException‛

Error ex:
Exception in thread "main" [Link]: Unable to
locate element: {"method":"partial link text","selector":"spider12"}

If the specified locator is matching with more than one element(duplicate) then
findElement() method returns first matching web Element.

cssSelector: sometime we cannot use the first 6 type of locator(tagName(), id(),


name(), className(),linkText(),paritialLinkText()) because it may be not supported.
Or it may not be given by developer or it may be duplicated.

Ex:
<html>
<body>
UN: <input type =‛text‛ ><br>
PW: <input type =‛Password‛>
</body>
</html>

In the above webpage to identify password filed, we cannot use the linkText() or
partialLinkText() as those not supported for the password filed. We can’t use the
id() , name() , className(), as it not given by the developer , we can’t use
tagName() as it is duplicate. In such scenario we can use the
cssSelector,(css(Cascaded style sheet)) with following syntax.

Htmltag[property =‛value‛]

Ex: input[type =’text’]


Input[type =’password’]
Vinay2ml@[Link]

publicclass cssselectorexpression {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link] ;
[Link]([Link]("input[type='text']")).sendKeys("vinay");
[Link]([Link]("input[type='password']")).sendKeys("Jugga")
;
[Link]();
}
}

Note: we can also use in Double cote in the ‚cssSelector(‚input[type =\‛password\‛])‛


but it we should be escape it using ‚\‛ backward slah.

Ex: input[id=’username’]
Input[class=’textField’]
Input[name=’username’]
Input[placeholder=’username’]

1) What are the attributes supported by the locator


Id(),name(), class().

2) Then how to use other attribute to identify the elements


We can use cssSelector() and xpath

Xpath: sometime even cssSelector() also can be duplicate.

Ex: <html>
<body>
FN:<input type=‛text‛><br>
LN:<input type =‛text‛>
</body>
</html>

In the above webpage both first name and last name as same cssexpression, hence we
can’t enter the lastname in such cases we use Xpath.

Xpath: it is path of the element in html tree.


1) While writing the xpath expression the specify the path using ‚/‛far
wordslash.
2) First forward ‘/’ slash represent beginning of html tree, it is called as
root.
3) After every ‚/‛ slash we must specify html tag of immediate child node only.
4) If there are duplicate elements are there then we can use index , it is with
in square bracket ‚[]‛ index start
Index is sequential no generated for duplicate sibling only. (Same tag name under
same
Parent element.

Body
|
Input
|
A
|
Vinay2ml@[Link]

----Div1  input1
 Input2
 A
----Div2 input 1
->input 2

In order to view the source code of the element it is called as inspecting the
element use Firebug, which is Add-on for firebox browser. In order to install it in
the firefox browser.
Tools->Add-on

Tree structure:
Html
↓----body
|--div
|---input A
|--input B
|
|____div
|--input c
|-input D
Absolute xpath: specify the complete path of the element is called as absolute xpath.

Absolute Xpath Elements


/html/body/div/input A, B, C, D
/html/body/div[1]/input A, B
/html/body/div[1]/input[1] A
/html/body/div[1]/input[2] B

Note: Navigating from parent node to the child node is called as forward traversing

Relative xpath: The absolute path is very lengthy instead of this we can use
releative xpath whith help of ‚//‛

‚/‛ represent immediate child


‚//‛ represent any child descended

Relative xpath: Element


//input A, B, C, D
//input[1] A, C
//input[2] B, D
//div[1]/input A, B
//div[1]/input[1] A
//div[1]/input[2] B
//div[2]/input C, D
//div[2]/input[1] C
//div[2]/input[2] D

What is difference between //a &


Vinay2ml@[Link]

1) Write the program to logout from the application without using any of
synchronization option?

publicclass withoutsync {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("username")).sendKeys("admin");
[Link]([Link]("pwd")).sendKeys("manager");
[Link]([Link]("loginButton")).click() ;
while(true)
{
try
{
[Link]([Link]("logoutLink")).click();
break;
}
catch(NoSuchElementException e)
{
}

[Link]();
}

2) Write a script login to the application without using click () method.

publicclass withoutclick {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("username")).sendKeys("admin");
[Link]([Link]("pwd")).sendKeys("manager");
[Link]([Link]("loginButton")).sendKeys([Link]);
[Link]();

3) Write a script to change text present in the textbox

publicclass changetext {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
WebElement un =[Link]([Link]("username"));
[Link]();
[Link]("vinay");
WebElement up =[Link]([Link]("password"));
Vinay2ml@[Link]

[Link]();
[Link]("Jugga");
[Link]();

}
4) Write a script change the text present in the text box without using the
clear() method ?

publicclass withoutclear
{
publicstaticvoid main(String[] args)
{
WebDriver driver =new FirefoxDriver();
[Link]("[Link]
WebElement un =[Link]([Link]("username"));
[Link]([Link],"a");
[Link]("manager");
[Link]();

}
5) Write a script to copy and paste text one box into another text box

publicclass copypaste {

publicstaticvoid main(String[] args) {


WebDriver driver =new FirefoxDriver();
[Link]("[Link]
//WebElement up =[Link]([Link]("password"));
//[Link]([Link],"a");
//[Link]([Link],"c");
//WebElement un =[Link]([Link]("username"));
//[Link]();
//[Link]([Link],"v");

WebElement up =[Link]([Link]("username"));
[Link]([Link],"a");
[Link]([Link],"c");
WebElement un =[Link]([Link]("password"));
[Link]();
[Link]([Link],"v");
[Link]();

}
1) Write a script to get text present in the text box.
Note: The text will be present inside an attribute called value, hence we
should use getAttribute() method.

publicclass gettext {
Vinay2ml@[Link]

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
String text
=[Link]([Link]("username")).getAttribute("value");
[Link](text);

String pass
=[Link]([Link]("password")).getAttribute("value");
[Link](pass);
[Link]();
}

Note: Can we return the pass word is present in the password filed using selenium?
Yes.
2) Write the script to get url of the link ?

publicclass geturl {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
String url = [Link]([Link]("Vtiger
Website")).getAttribute("href");
[Link](url);
[Link]();
}
}

3) Write a script to get tool tip text of the link from the [Link]

publicclass tooltiptext {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();

[Link]("[Link]
r=hp_nmenu_sub_electronics_0_iPad");
String str1 =[Link]([Link]("Apple 16GB iPad Mini
with Wi-Fi")).getAttribute("title");
[Link](str1);
[Link]();

4) Write a script to get the price of IPad min present in the [Link]
Vinay2ml@[Link]

5) Write a script to get phone no of Mumbai present in the [Link]

publicstaticvoid main(String[] args) {

WebDriver driver = new FirefoxDriver() ;


[Link]("[Link]

String xp1 ="//label[text()='Mumbai']/..//label[text() =': 022-


22618067']" ;
String text1 =[Link]([Link](xp1)).getText();
[Link](text1);

String xp2 ="//label[text()='For Internet Ticketing Complaints


']/..//label[text() =': care@[Link]']" ;
String text2 = [Link]([Link](xp2)).getText() ;
[Link](text2);

String text3 =[Link]([Link]("INDIAN RAILWAY


CATERING")).getAttribute("title") ;
[Link](text3);

6) Write a script select the checkbox whether that is selected or not

publicclass checkboxseleted {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
WebElement chebox1 = [Link]([Link]("keepLoggedInCheckBox"));
[Link]();
if([Link]()){
[Link]("Check box is selected");

}
else{
[Link]("check box is not selected");
}
[Link]();
}

5) How do you verify whether the button is enabled or not isEnabled() method
which returns Boolean value.

Ex:
Vinay2ml@[Link]

publicclass buttonenabled {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link]
WebElement btton = [Link]([Link]("loginButton")) ;
if([Link]()) {
[Link]("Button is enabled");
}
else
{
[Link]("button is not enabled");
}

6) Write a script to verify weather username text box is displayed or not in the
login page.

publicstaticvoid main(String[] args) {

WebDriver driver = new FirefoxDriver();


[Link]("[Link]
WebElement enab1=[Link]([Link]("username"));
if ([Link]())
{
[Link]("checkbox displayed");
}
else
{
[Link]("not displayed the checkbox");
}
[Link]();
}

Important Methods and web Element:


1) Click() ;
2) Clear() ;
3) sendKeys(character sequence…) ;
4) getAttributes(‚property‛) ;
5) getTitle();
6) isDisplayed();
7) isEnabled() ;
8) isSelected();
9) getLocation() return the coordinates x and y
10) getsize() return the width and height
11) getcssValue(String);
12) Submit();
Vinay2ml@[Link]

Find Elements(findElements()):
In order to get multiple elements from the webpage we use findElements method which
returns List<WebElement> , Generally we use xpath for this method.

Difference between findElement and findElements.


findElement() findElements()
1) It returns WebElement It returns List of WebElement
2) If locator is matching with n If locator is matching with n elements
elements(multiple) then it returns it returns List of webElemetns with size
first matching WebElement n and index 0 to n-1
3) If locator is matching with one If the locator is matching with one
elements it returns matching element , it returns List of webElement
WebElement with size 1 and index 0
4) If the locator is not matching The locator is not matching with any of
with any of the element then it the element then also it returns list of
will throw NoSuchElementException webelement with size 0 and without any
index, it also called as empty list.

We must import list from [Link] package and it is an interface.

Ex:
1) Count all the links present on the webpage and clicking on the first link .

publicclass countlinks {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
List<WebElement> alllinks ;
alllinks =[Link]([Link]("//a")) ;
int linkcount= [Link]();
[Link](linkcount);
WebElement link = [Link](2);
[Link]() ;
[Link]();

2) Write a script to print text of the links which is present on the [Link]
except empty string

publicclass googlelinks {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]") ;
List <WebElement> alllinks =[Link]([Link]("//a"));
int countlinks= [Link]();
Vinay2ml@[Link]

[Link](countlinks);
int j =0;
for(int i =0 ;i < countlinks ;i++){
WebElement link = [Link](i);
String linktext = [Link]();
int linksize =[Link]();
// [Link](linktext);

if(linksize >0){
j+=1 ;
[Link](linktext);

}
[Link](j);
[Link]();

3) Write a script to select all the checkbox present on the webpage in


[Link] ([Link]

publicclass checkboxselect {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]("[Link] ;
List<WebElement>chbox
=[Link]([Link]("//input[@type='Checkbox']")) ;
//Select the check box
for(int i=0 ; i <[Link](); i++){
[Link](i).click();
}
//Deselect the checbox using foreach
for(WebElement chbox1:chbox){
[Link]();
}
[Link]();
}

4) Write a script to select all the alternative checkbox present on the webpage
[Link]

publicclass alternativechboxselect {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]("[Link]
List<WebElement> chboxalt
=[Link]([Link]("//input[@type='Checkbox']"));
Vinay2ml@[Link]

for(int i =0 ;i < [Link]();i =i+2){


[Link](i).click();
}

[Link]();
}

5) Write a script to select all the checkbox present in the webpage in reverse
order.

publicclass reveresechkselect {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]().timeouts().implicitlyWait(10,[Link]) ;
[Link]("[Link] ;
List<WebElement> chboxreverse
=[Link]([Link]("//input[@type='Checkbox']")) ;
for(int i =[Link]()-1 ; i>=0 ;i--){
[Link](i).click();
}

[Link]();
}

6) Write a script to select first and last checkbox present on the webpage?

publicclass firstlastchbox {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link] ;
List<WebElement> firstlast
=[Link]([Link]("//input[@type='Checkbox']"));

[Link](0).click();
[Link]([Link]()-1).click() ;

7) Write a script to count no of images present in the webpage.

publicclass countimages {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
Vinay2ml@[Link]

[Link]().timeouts().implicitlyWait(10,[Link]) ;
[Link]("[Link] ;
List<WebElement> coutimgs = [Link]([Link]("//img")) ;
for(int i =0; i <[Link](); i++) {
String imges = [Link](i).getAttribute("title");
[Link](imges);
}

int count =[Link]() ;


[Link](count);

[Link]();
}

Handling the listbox: in webelement interface we do not have any appropriate method,
to handle the list box, in order to perform required action on list box we use Select
Class

Frist find the list boxElement ausing findElement() method, then pass it an
argument for Select class constructor and call any one of the select By method of the
select class as shown in the below.

publicclass Selectlistbox {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link]
WebElement elemt = [Link]([Link]("countrySelect"));
Select select =new Select(elemt);
[Link]("Australia");
[Link]();

}
We can use same selectBymethod to handle Multi select list box .

1) Write a script to count the number of option present in the list box.

publicclass countlist {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link] ;
WebElement listbox = [Link]([Link]("countrySelect")) ;
Select cslect =new Select(listbox) ;
int count = [Link]().size() ;
[Link](count);
Vinay2ml@[Link]

[Link]();

2) Write a script to print all the option present in the list box ([Link])

publicclass listoptionprint {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link]
WebElement listbox = [Link]([Link]("countrySelect"));
Select oselect = new Select(listbox);
int countlist = [Link]().size() ;
for(int i=0; i <countlist ; i++) {
[Link]([Link]().get(i).getText());

}
[Link]() ;

3) Write a script to print all the selected options with multi selected list box
in reverse order.

publicclass multiselectedreverese {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link]
WebElement listbox = [Link]([Link]("countrySelect"));
Select aselect =new Select(listbox);
for(int i =[Link]().size()-1; i >=0 ; i--)
{
[Link]([Link]().get(i).getText());
}

[Link]();

4) Write a script to print name and text of the first selected option present in
the multiselected list box

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10,[Link]) ;
[Link]("[Link]
Vinay2ml@[Link]

WebElement listbox = [Link]([Link]("countrySelect"));


Select aselect =new Select(listbox) ;
intcountsize =[Link]().size() ;
List<WebElement> selectoption = [Link]();
for(int i=0; i< [Link](); i++){
[Link]([Link](i).getText());

if([Link]()){
[Link]("yes multiple list box");
}
else{
[Link]("not a mulit select list box ");
}
}

3) Write a script verify whether the given list box is mulityselect list box
dropdown combo box.

publicclass multyorcombo {

publicstaticvoid main(String[] args) {

WebDriver driver = new FirefoxDriver();


[Link]().timeouts().implicitlyWait(10, [Link]);
[Link]("http:\\[Link]");
WebElement listbox = [Link]([Link]("countrySelect"));
Select listselect = new Select(listbox);
if([Link]()){
[Link]("is smultilistbox");
}
else{
[Link]("not multiselected");
}

[Link]();

4) Write a script to select all the option present in the mulitselect list box.

publicclass Selectedoptiosn {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10,[Link]) ;
[Link]("[Link]
WebElement listbox = [Link]([Link]("countrySelect"));
Vinay2ml@[Link]

Select aselect =new Select(listbox) ;


intcountsize =[Link]().size() ;
List<WebElement> selectoption = [Link]();
for(int i=0; i< [Link](); i++){
[Link]([Link](i).getText());

if([Link]()){
[Link]("yes multiple list box");
}
else{
[Link]("not a mulit select list box ");
}
[Link]();
}

Note: in Select class we gave deselect() methods, which is simllar to


selectByMethods() such as
deSelectAll();
deSeletByValue() ;
deSelectByIndex();
deSelectByvisibleText() ;

But there is no select All method in order to Select all the option we should
write a looping code as shown in the above example.

5) Write a script to search for the Specified option present in the List box.

publicclass specifiedoption {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver();
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link]
WebElement listbox = [Link]([Link]("countrySelect"));
String eval ="Saab" ;
String msg ="not found" ;
Select selectmsg = new Select(listbox);
List<WebElement> listitem = [Link]() ;
for(int i =0 ; i< [Link]() ; i++) {
String avalue =[Link](i).getText() ;
if([Link](avalue)){
msg ="Found @index :"+ i ;
break ;
}
}
[Link](msg);
Vinay2ml@[Link]

[Link]();
}

1) What is dynamic list box how to handle it , list box whoes content is keep
changing during runtime is called as dynamic list box, in order to handle
them use Select class itself. Along with Explicit wait.

Note: Most of the class dynamic element or developed using AJAX (Asynchrons
java script and XML) technology to handle Ajax element we use Explicit
wait().

Ex: Selecting the required in country list box which in state then
selecting respective state, in the state list box it is dynamic .

publicclass dyanmiclistbox {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10, [Link]);
[Link]("[Link]
WebElement listboxcountry = [Link]([Link]("s1")) ;
Select clist = new Select(listboxcountry) ;
[Link]("IND") ;
for(int i =0; i< [Link]().size(); i++)
{
[Link]([Link]().get(i).getText());
}

WebElement stlistbox = [Link]([Link]("state"));


Select slist = new Select(stlistbox) ;
[Link]([Link]().size());
for(int i =0 ;i < [Link]().size(); i++){

[Link]([Link]().get(i).getAttribute("value"));
}

WebDriverWait wait = new WebDriverWait(driver, 15);


By b = [Link]("//option[@value='Gujarat']");
[Link]([Link](b));
[Link]("Madhya Pradesh") ;

//[Link]("//option[@value='Gujarat']") ;

[Link]();

Handling customized List box any list box which is developed without using
Select HTML tag is called as customized list box.
Vinay2ml@[Link]

We can’t handle the customized list box, using Select class we try to use
it, we get unexpected tag name Exception.

In order to handle it we use Send key’s method itself as shown


below.

publicclass custimzedlistbox {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link]
WebElement listbox1 =
[Link]([Link]("BE_flight_origin_city"));
[Link]("Bangalore");
[Link]([Link]);

WebElement arlist = [Link]([Link]("BE_flight_arrival_city"))


;
[Link]("Hyderabad") ;
[Link]([Link]);

2) Write a script to search selenium in google and print all the autosuggested
options.

publicclass searchprintautolist {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20,[Link]) ;
[Link]("http:\\[Link]") ;
WebElement intextbox = [Link]([Link]("gbqfq"));
[Link]("Selenium") ;

String xp = "//div[@class='sbqs_c']" ;
List<WebElement> autolist = [Link]([Link](xp));
for(int i =0 ; i< [Link](); i++){
//[Link]([Link](i).getAttribute("class"));
[Link]([Link](i).getText()) ;
}

[Link]();
}

3) Write a script to search selenium in the google and select the


autosuggestion if it contains the tutorial then click or select.
Vinay2ml@[Link]

publicclass chkautolist {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20, [Link]);
[Link]("http:\\[Link]") ;
WebElement inputbox = [Link]([Link]("//input[@id
='gbqfq']"));
[Link]("Selenium");
List<WebElement> autolist =
[Link]([Link]("//div[@class='sbqs_c']"));
for(int i =0; i < [Link](); i++){
String actal =[Link](i).getText();
[Link](actal);
if ([Link]("tutorial")){
[Link](i).click();
break ;
}
}
}

Note: if we try to perform any action on the element after the Element is reloaded or
disappeared or page refresh then we get StaleElementRefrence Exception

Drop down Menu: it is an element on which of we move the mouse pointer it will
display list of option (submenu).

In order to handle drop down menu we use Actions() class. In order to


move the mouse pointer on the element we use. Move to element method of Action class
But whenever we call any action class it is mandatory, that we call perform().method

Ex:
Vinay2ml@[Link]

1) Select ‚basic back‛ option menu in present in the [Link]


([Link]
publicclass Dropdownmenuaction {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20,[Link]);
[Link]("[Link]
WebElement menu = [Link]([Link]("//span[text()='About
Company']"));
Actions actions = new Actions(driver);
[Link](menu).perform() ;

//[Link]([Link]("//a[text()='Basic Facts']")).click();
[Link]([Link]("//a[text() ='Areas of
Expertise']")).click() ;
[Link]();

Context Menu: The list of option displayed when you right click on the page is called
as context menu:

In order to right click on the webpage, we use context click method of


Action class(contextclick) But selenium cannot recognize option present in the
context menu.

In order to select the required option present in the context menu. Type the short
cut keys ‚such as ‚T‛ for new Tab, ‚w‛ for new Window, etc.. using sendkeys() methods
of Actions class as shown below.

publicclass contextmenu {

publicstaticvoid main(String[] args) {


Vinay2ml@[Link]

WebDriver driver = new FirefoxDriver() ;


[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("[Link]
WebElement homepage = [Link]([Link]("//span[text() ='Home
Page']"));
Actions actionmenu = new Actions(driver);
[Link](homepage).perform() ;
[Link]("w").perform() ;

[Link]();

Performing Drag and drop in order to another location we use drag and drop method of
the action class.
[Link](source, target);

2) Write a script to drag1 to block 1 and drop it on to block3 which is


presenting .
[Link]

publicclass dragdrop {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20,[Link]);
[Link]("[Link]
google-like-drag-drop/[Link]");
WebElement block1 = [Link]([Link]("//h1[text()='Block
1']"));

WebElement block3 = [Link]([Link]("//h1[text()


='Block 3']"));
Actions act =new Actions(driver);
[Link](block1, block3).perform();

[Link]();

Note: Actions class can also be used [Link] statement.


[Link](webelemnet).perform()

Handling Pop-up:
Vinay2ml@[Link]

In selenium performing action on the pop-up depended on the type of the pop-up.
Some of the pop-up cannot be handled by selenium in such cases we use alternative
rd
option and 3 party tools.

In order to Clearyidentifypop-up type always use the browser. It


is opened by selenium, we can categorize the pop-up window following types.
1) Alert confirmation
2) Hidden Division pop-up
3) Page on-load pop-up
4) File upload pop-up
5) File download pop-up
6) Child browser pop-up
7) Window pop-up

1) Write a script take screen shot of the application .png format

publicclass captureimage {

publicstaticvoid main(String[] args) throws IOException {


WebDriver driver = new FirefoxDriver();
[Link]().timeouts().implicitlyWait(10,[Link]);
[Link]("http:\\[Link]");

EventFiringWebDriver edriver = new EventFiringWebDriver(driver);


File srcFile = [Link]([Link]);

[Link](srcFile, new File("C://test/[Link]"));


[Link]();

Note:

1. The getScreenShotAs() method takes complete Screenshot of the webpage( it will


automatically does the scrolling .
2. In selenium there is no option to take the screen shot of specific element.
3. We cannot take the screen shot of the only logo present on the webpage.

Alert and confirmation pop-up:


Vinay2ml@[Link]

Characteristics:
1) We can move the pop-up
2) We cannot inspect the pop-up
3) It will have ok button
4) If the ok and cancel button this is confirmation pop-up.

In order to handle the pop-up first we should transfer control to the Alert pop-up
using switch start it returns the object of type alert and we can use following
method of Alert class.
1) GetText() used to get the text of the pop-up.
2) Accept – used to click on ‚ok’ button
3) Dismiss- > used to click on cancel button

Note:
1) If Alert pop-up is not present it will throw NoAlretPresentException:
2) After closing the alert pop-up control will be transferred back to the
mainpage automatically.
3) There cannot be multiple alert pop-up at the same time, that is if multiple
pop –up displayed at the same time it will be other than the Alert pop-up.
4) Most of the cases will be hidden division pop-up or child browser pop-up.
5) If multiple alert pop-up displayed, then each time we should use switch to
statement.

Ex:
publicclass alertconfimation {

publicstaticvoid main(String[] args) {

WebDriver driver = new FirefoxDriver() ;


[Link]().timeouts().implicitlyWait(10, [Link]);
[Link]("[Link]

//[Link]([Link]("button")).click();
//[Link]([Link]("button")).click() ;
//[Link]([Link]("input[id ='button']")).click() ;
[Link]([Link]("//input[@id ='button']")).click() ;

try{
Vinay2ml@[Link]

Alert alret = [Link]().alert();


[Link]("Alert is present");
String msg = [Link]() ;
[Link](msg);
[Link]() ;

}
catch(NoAlertPresentException e ){
[Link]("Alret is not present");
}
[Link]();
}

Note: Java script pop-up is Alert pop –up

Hidden division pop-up:


Characteristics:
1) Most of the case we cannot move the pop-up
2) We can inspect the pop-up
3) It can have any type of buttons or buttons may not be present
4) Most of the case’s it will colorful

Since we are allowed to inspect the element we can handle this pop-up using
findElement() method itself.

Note: This is called hidden division pop-up because it is created using Html tag div
and initially its hidden (Display none)
2) Calendar pop-up is type of hidden division pop-up

Ex:
publicclass hiddendivisionpopup {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20,[Link]) ;
[Link]("[Link] ;
//[Link]([Link]("input[type='image']")).click() ;
[Link]([Link]("//input[@title ='Upload file']")).click() ;

/*input id="login" type="text" size="22" name="login"


Any of the below find element can be used.
[Link]("login");
[Link]("login");
[Link]("input[id = 'login']")
xpath = //input[@id ='login'] */

try {
[Link]([Link]("login")).sendKeys("vinay2ml@[Link]") ;
[Link]([Link]("password")).sendKeys("nokianokia123") ;
[Link]([Link]("password2")).sendKeys("nokianokia123") ;
Vinay2ml@[Link]

[Link]([Link]("//button[@onclick='return
doSignUp();']")).click();
//id="loginErrorMsg" class="body" align="left" style="color:red"
colspan="2"
String msg =
[Link]([Link]("loginErrorMsg")).getAttribute("id");

if([Link]("loginErrorMsg")){
[Link]([Link]("I already have account")).click()
;
}

[Link]([Link]("login")).sendKeys("vinay2ml@[Link]");
[Link]([Link]("password")).sendKeys("nokianokia123") ;
[Link]([Link]("//button[@onclick='return
doLogIn();']")).click() ;

catch(NoSuchElementException e){
[Link]("popup is not displayed");
}
}

1) How do you handle the calendar pop-up ?


It is hidden division pop-up we handle it findElement() method itself.

publicclass calenderhandle {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20,[Link]) ;
[Link]("[Link]

[Link]([Link]("//input[@id='BE_flight_depart_date']")).click();
[Link]([Link]("//a[@id='a_2014_10_15']")).click() ;

2) How do you enter into the Textbox without using SendKeys() using java script.

Using JavaScript we can enter the text in the text box even if the textbox is
disabled.
Vinay2ml@[Link]

3) Write a script to select future date in the calendar without writing the
navigation code.

4) Write a script to select today’s date in the calendar presetting in [Link]


5)

Page on load pop-up:

1) We can move the pop-up


2) We cannotinspect the pop-up
3) It will have ‚ok‛ and ‚cancel‛ button
4) It will have username and password filed.

Note: this is pop-up is displayed while loading the webpage, hence it is called
as page onload pop-up.

Solution: Selenium can ‘not perform any action on page on-load pop-up in order to
handle it the specify user name and password in the url itself as shown in below.

Handling Database:
While testing the application some time we need to verify the data present in
the database also. In order to do this we should have the following information
of the database such as :
1) Data base type
2) Data base location
3) Username and password
4) Login to data base
5) Table structure (Data schema) and SQL knowledge

Ex: Actitime Application:


1) Data base type = MS Access
2) Data base location = ‚C:\Program Files (x86)\actiTIME\database\‛
3) Username and password : no username and pass
4) Table structure : ex: access_right, at_user, customer etc..
Vinay2ml@[Link]

5) Ex: sql statement :‛Select * from access_right‛

While retrieving the information from database programaitcally, we should provide


information such as database type, location , username and password . which are
called as connection string :

The connection string can be stored in a system variable called DSN (Data
source name)

In order to see the DSN available in the system


StartData base connection
Vinay2ml@[Link]

We can create our own DSN connect to any required data base before creating the DSN
assume that required database driver installed in the system .

Steps to create a DSN:


1) Go to start type: data source (ODBC) and select DSN

2) Specify the data source name :


3)
Vinay2ml@[Link]

Note: in order to specify the username and password click on Advanced button.

1) Java code to open and close database connection.

publicclass connetingdatabase {

publicstaticvoid main(String[] args) throws SQLException {

Connection con = [Link]("jdbc:odbc:actitime") ;


[Link]() ;
[Link]("connection successfuly done");

2) Write a code to count the no of column present in the table and also print
name of the column

publicclass countcolumnname {
publicstaticvoid main(String[] args) throws SQLException {
Connection c = [Link]("jdbc:odbc:actitime");
String sql = "select * from customer" ;
ResultSet r = [Link]().executeQuery(sql);
int cc = [Link]().getColumnCount() ;
[Link](cc);

for (int i =1 ;i <= cc ; i++) {


String cname = [Link]().getColumnName(i) ;
[Link](cname);
}

[Link]() ;

}
Vinay2ml@[Link]

3) Write a code to print the content of the specified table

publicclass specifiedtable {

publicstaticvoid main(String[] args) throws SQLException {


Connection con = [Link]("jdbc:odbc:actitime") ;
String sql = "Select * from customer" ;
ResultSet row = [Link]().executeQuery(sql) ;
int cc = [Link]().getColumnCount();
while([Link]()){

for(int i = 1; i<=cc ; i++)


{
String data = [Link](i) ;
[Link](data);
}
}

[Link]();

Note:
1) The above program can be used on any database on any system only DSN name
changes.
2) In JDBC column index start from 1 like xpath.
3) ResultSet do not have the hasnext() method ,next() method itself perform the
action of the hasnext() method
4) To retrieve data present in the cell of the table we alwasys use getString()
method irrespective of the cell data type. Later we may use wrapper class or
type casting to convert the data into required type.

TestNG : (Next Generation)

TestNG is a unit testing tool. Basically used by developer to perform white box
testing that is every requirement given by the customer , developer develops a java
class which will be called as business class. If there are multiple requirements a
there will be multiple business class.

In order to test all the business class ( white box testing ) developer
develops corresponding test class in order to run all the test class together(Batch
execution ) developer uses TestNG. Which will also generate execution result
automatically in html format it also as other built in functions , such as :
Assertion , Re-execution of the failure scripts etc..

In selenium for every manual test cases we develop automation script in java
class. In order to execute all the selenium scripts to generate execution results
etc. we also use TestNg.
Vinay2ml@[Link]

Installing TestNG :
1) Open Eclipse go to help
2) Help Eclipse Marketplace Search  Test NG

3) Click install button of Test NG for Eclipse


4) Accept->Finish -> ok for warning message
5) Yes –on the confirmation.

Note: if Eclipse marketplace is not available then select ‚install New software‛
under the help menu . clickAdd specify the name as TestNG location as :
[Link] Get the location url from [Link] web site.

Configuring the java project:


1) Right click on the java project
2) Select- properites -> java build path -> Libraries Add libraries Select Test NG Finish—OK.

3)

Test NG class:

1) It is a java class which contains test Method .


Vinay2ml@[Link]

2) Any method which is written below Test Annotation is called as Test Method.
3) @Test is called as Test Annotation syntactic metadata

Whenever we run any TestNG class it automatically generate the result in Html format
([Link]) or index html. Inside (Test-output) folder of the java
project

If the test-output folder is not present it will create it , if already present it


will be overwrites . in order to write any information into html report as wee as
console use log method of [Link] as shown in the below.

package [Link];

import [Link];
import [Link];
import [Link];

publicclass demo {

privatestaticfinal ITestResult True = null;

@Test
publicvoid testA()
{
[Link]("Login");
Vinay2ml@[Link]

Note: in TestNG main method is present in [Link] .

1) Can we have multiple Test Method in the TestNG class ?


Ans: Yes

2) If there are multiple Test method what is the order of execution ?


Ans: Alphabetical order

3) Then how do you execute Test method which is required order ?


Using Priority

package [Link];

import [Link];
import [Link];

publicclass priorityexp {

@Test(priority = 2)
publicvoid Deletecustomer()
{
[Link]("Delete the custoer") ;

@Test( priority = 3)
publicvoid Editcustomer()
{
[Link]("Edit the custoer ");

}
@Test(priority = 1)
publicvoid Registercustomer()
{
[Link]("Create the customer ");
}

}
Note:
1) giving the priority is not mandatory, if it is not provided its priority will
be zero (0)
2) it can give the negative number also for priority
3) Then priority is need not be in sequential order
4) The priority should always a number , it always execute in ascending order.

1) How do you create dependency in the TestNG


Ans: dependsonMethods
Vinay2ml@[Link]

Ex:
package [Link];

import [Link];
import [Link];
import [Link];

publicclass dependsonmethodex {

@Test(dependsOnMethods ="Registercustor")
publicvoid deletecustoer()
{
[Link]("Delete custer depend on register") ;
}

@Test
publicvoid Registercustor()
{
[Link]("Register custoremr ") ;
[Link](false) ;

}
}

Note: in the above ex: frist it wil try to execute delete customer (because of
alphabetical order), but because of dependency it will execute first
registercustomer method. Which will fail during the runtime , hence it will
skip execution of delete customer method.
output:

[TestNG] Running:
C:\Users\viml\AppData\Local\Temp\testng-eclipse-142572682\[Link]

FAILED: Registercustor

SKIPPED: deletecustoer

===============================================
Default test
Tests run: 2, Failures: 1, Skips: 1

2) When the TestNG class is skip -> if the dependsonMethod is failed it will
skip the test method.

3) How to create multiple dependency or how to make a method depend on multiple


methods ?
Ans: (dependsOnMethods ={‚Registercuster‛,‛Editcostmer‛})
1) How do you perform validation in TestNG ?
Vinay2ml@[Link]

Using Assert class validation refers to comparing actual value with expected
value and reporting the status.

Ex:
package [Link];

import [Link];
import [Link];
import [Link];

publicclass assertequalscheck {

@Test
publicvoid Registercustormer(){

[Link]("Login") ;
[Link]("Register custmer") ;
String msg = "Created customer" ;
String emsg ="Created not customer" ;
[Link](msg, emsg);
[Link]("Logout");
}
}

Note: when we use Assertion it will compare the actual value with expected
value of both are same then the status will be pass, and it will continue the
execution of the reaming statement.
If actual and expected values are different the status will be failed
and it will stop the current test method execution. (But it will continue
execution reaming methods).

Important methods of Assert class and static methods.


1) assertEquals()
2) assertNotEquals()
3) assertTrue()
4) assertFalse()
5) assertNull()

1) How do you ensure that Test will continue execution ever after the
verification failed.?
Using SoftAssert().
Ex:
publicclass usingsoftassert {

@Test
publicvoid registercustormer()
{
SoftAssert softassert = new SoftAssert() ;
[Link]("Login") ;
[Link]("register");
String msg ="created customer" ;
String emsg ="created" ;
[Link](msg, emsg);
Vinay2ml@[Link]

[Link]("logout") ;
[Link]();

2) What is the difference between Assert and softAssert


Assert softAssert
1) It will stop the current method 1) It will not stop the current
execution when the verification method execution when the
failed verification failed
2) All the method are static ,we 2) All the methods are non-static,
don’t create the object we have to create the object
3) We do not call assertAll() 3)we must call assertAll() method
method

Note: while verifying the important or critical features use assert that is the steps
where can not procced, because of the failure like blocker defect or showstopper. But
otherwise we can use softassert() method.

Important Annotiaon of TestNG:


1) @Test : this indicate the Test method
2) @BeforeMethod : This method will be executed before the execution of every
test method
3) @AfterMethod : This method will be executed after the execution of every test
method.
4) BeforeClass : This method will be executed only once beginning of the class
5) AfterClass : This method will be executed only once at the end of the class.
Ex:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass DemoA {
@BeforeClass
publicvoid openApp()
{
[Link]("open the logs ",true);
}

@AfterClass
publicvoid closeApp()
{
[Link]("close the app",true);
}
Vinay2ml@[Link]

@BeforeMethod
publicvoid login()
{
[Link]("Login ",true);
}

@AfterMethod
publicvoid logout()
{
[Link]("logout",true);
}

@Test
publicvoid createcustomer()
{
[Link]("Registercusotmer",true);
}

@Test
publicvoid Deletecustomer()
{
[Link]("Delete coustomer",true);

}
}
Note: Other Annotation of TestNG ([Link]

1) @BeforeSuite
2) @AfterSuite
3) @BeforeTest
4) @AfterTest
5) @BeforeGroups
6) @AfterGroups
7) @Factory
8) @Listener
9) @parameters
10)@Dataprovider

Inheritance in TestNG

While developing Automation scriot for every manual testcase we write TestNG class
that is if we are autmomating 100 manual testcase we create 100 testNG class.
In every TestNG class ther may be common steps, such as Login and logout
.instead of writing those methods again and again we can use inheritance concept.
That is we develeop all the common methods in the parent class then inherted. In all
the TestNG class as show in the below example.

SupertestNG. Java

Login() Logout()
Vinay2ml@[Link]

[Link] [Link]

Createdcustomer() Deletedcustomer

(DemoB and DemoC inherited the supertestNG class)

---------------------------------------[Link]------------------------------
package [Link];

import [Link];
import [Link];
import [Link];

publicclass SupertestNG
{
@BeforeMethod
publicvoid login()
{
[Link]("Login ", true) ;

@AfterMethod
publicvoid logout()
{
[Link]("Logout", true) ;
}
}
[Link]

package [Link];

import [Link];
import [Link];

publicclass DemoB extends SupertestNG


{
@Test
publicvoid createcustomer()
{
[Link]("Create customer", true) ;
}

------------------------[Link]-----------------------------
package [Link];
Vinay2ml@[Link]

import [Link];
import [Link];

publicclass demoC extends SupertestNG


{
@Test
publicvoid deletecustormer()
{
[Link]("Delete customer", true) ;

}
}

Output:
Login
Create customer
Logout
Login
Delete customer
Logout

===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Test suite:
It is an xml file which contains list of all the TestNG class which are to be
executed .

Creating the suite:


Vinay2ml@[Link]

1) Right click on the java project ->TestNGConvert to TestNG

2) It create [Link] file inside the java project .Xml contains :

<suitename="Suite"parallel="none">
<testname="Test">
<classes>
<classname="[Link]"/>
<classname="[Link]"/>
</classes>
</test>
</suite>

In order to execute the TestNG suite Right click on the [Link] go to Run as
Select TestNG suite.

1) Script execution is successful But still we want to fail the script explicitly
?
[Link]()

Ex: package [Link];

import [Link];
import [Link];
import [Link];

publicclass demoC extends SupertestNG


{
@Test
Vinay2ml@[Link]

publicvoid deletecustormer()
{
[Link]("Delete customer", true) ;
[Link]() ;
}
}

2) How do you re-execute only the failed script, when ever ther is failure in the
execution TestNG automatically creates [Link] file inside the test-
out floder which contains list of all the failed testNG class or method. So in
order to execute only the failed script Right click on the xml file go to run
as select TestNG suite.

3) How do you execute a method multiple times ?


@Test(invocationCount =5)

Ex:

package [Link];

import [Link];
import [Link];

publicclass DemoB extends SupertestNG


{

@Test(invocationCount =5)
publicvoid createcustomer()
{
[Link]("Create customer", true) ;
}

Output:

Login
Create customer
Logout
Login
Create customer
Logout
Login
Create customer
Logout
Login
Create customer
Logout
Vinay2ml@[Link]

Login
Create customer
Logout
PASSED: createcustomer
PASSED: createcustomer
PASSED: createcustomer
PASSED: createcustomer
PASSED: createcustomer

===============================================
Default test
Tests run: 5, Failures: 0, Skips: 0

4) How do you execute a method multiple times with different input?


dataprovider=‛logindata‛

ex:

package [Link];

import [Link];
import [Link];
import [Link];

publicclass dataproviderex {

@DataProvider(name ="logindata")
public Object[][] getData()
{
Object[][] data = new Object[2][2] ;
data[0][0] ="admin" ;
data[0][1] = 1234 ;
data[1][0] ="userA" ;
data[1][1] =3455;
return data ;

@Test(dataProvider="logindata")
publicvoid loginlogout(String un, int pin)
{
[Link]("enter un "+un, true) ;
[Link]("Enter pin" +pin, true) ;
[Link]("Click login ",true) ;
[Link]("click logout", true) ;
}
}

Output:

enter un admin
Enter pin1234
Click login
click logout
Vinay2ml@[Link]

enter un userA
Enter pin3455
Click login
click logout
PASSED: loginlogout("admin", 1234)
PASSED: loginlogout("userA", 3455)

===============================================
Default test
Tests run: 2, Failures: 0, Skips: 0
===============================================

Note: in automation testing we use XL file as a source to test the application


with multiple inputs (data driven testing) because dataprovider as following
issues :
1) Size of the data is fixed
2) Maintaining large test data is very difficult ex: 100 users
3) We can’t reuse the data provider, if it present in the different class

Parallel execution using TestNG:

While performing browser compatibility testing execute the same script on


multiple browser, but of execute in sequential order , it will time
consuming , instead of this we can use TestNG to execute the script in
parallel.

Content of the TestNG class:

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass DemoD {

@Parameters({"browser"})
@Test
publicvoid testD(String browser)
{
WebDriver driver ;
if([Link]("GC"))
{
[Link]("[Link]",
"C:/selenium/Selenium-Dump/[Link]") ;
Vinay2ml@[Link]

driver = new ChromeDriver() ;

}
else
{
driver = new FirefoxDriver() ;

[Link]().timeouts().implicitlyWait(20,[Link]) ;
[Link]("[Link] ;
for(int i =1 ;i <=100 ; i++)
{
[Link]([Link]("username")).sendKeys("vinayjugga") ;
[Link]([Link]("username")).clear();
}
[Link]() ;
}

Note: we can’t execute above class directly because testMethod is taking the
parameter we should always run this from the TestNG suite.
[Link]

<suitename="Suite"parallel="tests">
<testname="GCTest">
<parametername="browser"value="GC"/>
<classes>

<classname="[Link]"/>
</classes>
</test><!-- Test -->

<testname="FFTest">
<parametername="browser"value="FF"/>
<classes>

<classname="[Link]"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->

Encapsulation: binding the data member and member function together in a


secure way is called encapsulation.

Ex:

package [Link];
Vinay2ml@[Link]

import [Link];

import [Link];
import [Link];

publicclass encapsulationex {

private WebElement un ;
private WebDriver driver ;

publicdemo()
{
un = [Link]([Link]("usename")) ;
}

publicvoid setter(String username)


{
[Link](username);
}
}

Automation frame work:

It is a set of Rules guidelines and best practice to automated application in


automation frame work. There are 3 stages.

1) Framework Design
2) Framework Implementation
3) Framework Execution

The above stages depends on type of the framework which is used in the automation.

We can broadly categorized the framework types as specified below irrespective of the
automation tools.

1) Linear automation Framework


2) Data driven automation Framework
3) Method driven automation Framework it is also called as Function drivern or
action driven
4) Module driven Automation framework
5) Keyword driven Automation Framework
6) Hybrid Automation Framework

Note: with respect to selenium there are popular frameworks which are implemented
using any one of the above types.

Ex: Page object module (POM)

Robot framework, cucumber framework.


Vinay2ml@[Link]

Framework Design: Senior automation engineer or leads with their past experience will
design the automation framework.

1) They list of out of all the software files which are required for the
automation and then specify the folder structure and their purpose.
2) Required software:
1) JDK
2) Ecliepse +TestNG plugin
3) Firefox +Firebug +Firepath plugin
4) AutoIt
5) Google chrome browser
6) MS office

Note: ensure that all the mentioned software are installed and there are updated .

Required files:

1) Selenium server stand alone .jar file


2) Apache and POI jar files
3) [Link] file
4) [Link] file

Configuring the Framework:

1) Create floder c:\AWS


2) In Eclipse IDE go to file->Switch workspace and select the AWS folder
3) Create a new Java project –specify the name ex: Automation

In the automation framework we will be using the below files:

1) .jar
2) .exe
3) .xls
4) .xml
5) .html
6) .bat
7) .class
8) .java

Note: Except first 3 types of files all the other files will have predefined location
such as :

Src : .java files

Bin: .class files etc..

In the java project folder we should create 3 floders to store the first 3 types of
files.

C:\AWS\Automation

Create the folders : ex: Exefiles, Excelfiles, Jarfiles.


Vinay2ml@[Link]

1) Copy the selenium jar files into jarfile floder and [Link] and
[Link] copy paste into the exefiles.

Note: if we write any AuotIT script the framework implementation then autoIt script
also stored into the exefiles.

Simllarly if we any xlfiles for the test data it will be copy paste into the
excelfiles folder.

In eclipse IDE right click on the java project and Refresh which will display newly
created floder.
Vinay2ml@[Link]

Select all the jar files in the Java build path select library stack and click Add
external Jar files

Click on Add library select TestNg click finish

Implementation of the framework:

This is the actual stage where we develop the required Methods and convert the Manual
test case’s into automation Script.

Java Design pattern:

Before writing any code developer will consult architecture for the design of the
application in java 250 + Design solution are ready available which are called as
java design pattern .

Some of the famous and frequent used java design pattern are

1) Signleton
2) Multiton
3) Factory
4) Page object Module

For developing the web application page object model is best suitable.

Page object Module:

This is the one of the java design pattern where the below rules to develop the
webpage.
Vinay2ml@[Link]

1) For every webpage present in the application developer develops 1 Java class.
2) Every java class should contain data members and constructor and member
function
3) Data member represent the elements present on the webpage and all the data
member should be private.
4) Constructor is used to initialize the element present on the webpage this
process is called as page decoration. In page object module we use parameter
side constructor.
5) All the method should be public and they are used to perform action on the
element in automation also we use page object module concept to test the
webpage.

Ex:

import [Link];
import [Link];
import [Link];

publicclass loginpage
{
private WebElement untexbox ;

public loginpage(WebDriver driver)


{
untexbox = [Link]([Link]("username")) ;
}

publicvoid setUserName(String un)


{
[Link](un) ;
}

public String getUserName()


{
[Link]("value");
}
}

Abstraction: hiding the implementation from the end user generally called as
abstraction .

We use this concept to reduce the burden on the end user and also reduce the
maintaince.

Ex: Instead of developing setter and getter method for every field we develop the
method based on the functionality

Ex: instead of developing 3 method to handle username and password and login button
sparetly , we develop method as shown below .
Vinay2ml@[Link]

publicclass loginpage
{
private WebElement untexbox ;
private WebElement loginbutton;

publicvoid login(String un, String pw)


{
[Link](un) ;
[Link](pw) ;
[Link]() ;
}

The end user just call a method to perform the login operation on the application
without knowing the actual implementation of the code.

Ex:

import [Link];

import [Link];
import [Link];

publicclass loginusage {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20, [Link]) ;
[Link]("[Link] ;
LoginPage loginpage = new LoginPage(driver) ;
[Link]("admin", "manager");

Page Factory:

It is a selenium class which implements page object module concept in selenium.

Generally when we try to initialize the element in the constructor at the beginning
only so we may get exception, because the element may not be present at that time.

Ex:

Error msg is displayed only entering after the criditianls popup is displayed only
click in on after click login button get exception.
Vinay2ml@[Link]

While handling the very large webpage where it has too many elements will drastically
increase total length of the constructor.

Loading all the elements into the memory at a time will affect performance of the
script also to overcome the above issue we use Page factory.

In page factory we should declare the element using @FindBy Annoation and we use
initElements() methods to initialize all these elements during runtime instead of the
initial time this process is called as late binding or lassie initialization

Ex:

[Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass LoginPage
{
@FindBy(id ="username")
private WebElement untexbox ;

@FindBy(name ="pwd")
private WebElement passwd;

@FindBy(id ="loginButton")
private WebElement loginbutton ;

@FindBy(className ="errormsg")
private WebElement emsg;

public LoginPage(WebDriver driver)


{
[Link](driver, this);
}

/*public LoginPage(WebDriver driver)


{
untexbox = [Link]([Link]("username")) ;
untexbox = [Link]([Link]("pwd"));
loginbutton =[Link]([Link]("loginButton"));
}
*/
/*public void setUserName(String un)
{
[Link](un) ;
}

public String getUserName()


Vinay2ml@[Link]

{
return [Link]("value");
}
*/

publicvoid login(String un, String pw)


{
[Link](un) ;
[Link](pw) ;
[Link]() ;
}

public String printErrorMsg()


{

String emsg1 = [Link]() ;


[Link](emsg1);
return emsg1;
}
}

mport [Link];

import [Link];
import [Link];

publicclass loginusage {

publicstaticvoid main(String[] args) {


WebDriver driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20, [Link]) ;
[Link]("[Link] ;
LoginPage loginpage = new LoginPage(driver) ;
[Link]("admin", "manager1");
[Link]();

How do you handle multiple elements using FindBy Annoation

@FindBy(xpath =‛//a‛)

Private List<WebElement> alllinks;

Note: The above statement equivalent to findElements() methods..

What is the limitation of findBy Annotation:

@FindBy we can’t use variable in FindBy Annotation. While specifying the value of the
locator .
Vinay2ml@[Link]

Ex: String xp =‛//a‛

@FindBy(xpath =xp) //Error

Private webElement link:

Developing Page object Module:

Developing Sample test case :[Link]

1) Testcase_ID :ActiveTime_LoginLogout()
Steps:
 Enter valid username
 Enter valid password
 Enter on login button
 Click on logout link
2) TestCase_ID: ActiveTime_CreateBilling()
Steps:
Enter valid user name and password
Click on login button
Click on setting and then click on Billing types
click on Create Billing Types
Enter the name ex: Automation and click on create Billing Type
Verify that following success Message displayed
Msg =‛Billing type has been successfully created‛
Click on logout
3) TestCase ID: ActiveTime_DeleteBilling()
Steps:
 Login to activetime with valid username and password
 Click on settings and click on billing types
 Click on delete link on Autoatmion click ok on confirmation pop-up
 Verify that following msg is displayed
 Msg=‛Billing type has been successfully deleted.
 Click on logout link

Note:

1) Execute the testcase manually at least once , its given more clarity on the
testcase should be automated
2) For the given testcase note down the elements and action perform on those
Elements based on the webpages
3) Some of the elements will be present in multiple webpages such as headers and
footers.

Ex: Time track menu , Settings, helps, logout etc.


Vinay2ml@[Link]

Instead of storing and writing method in every class we use inheritance


concept. That is we created superclass, which is called as Basepage and then
we make all other class in the page object module to extends Base page class,
except login page.

1) Pages and Class:

Page1: LoginPage
Elements: usernametextbox, pwtextbox, loginbutton
Methods:
Method1-------login()
 Enter un
 Enter pw
 Click login

[Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass LoginPage
{
@FindBy(id ="username")
private WebElement untexbox ;

@FindBy(name ="pwd")
private WebElement passwd;

@FindBy(id ="loginButton")
private WebElement loginbutton ;

@FindBy(className ="errormsg")
private WebElement emsg;

public LoginPage(WebDriver driver)


{
[Link](driver, this);
}

publicvoid login(String un, String pw)


{
[Link](un) ;
[Link](pw) ;
[Link]() ;
}
Vinay2ml@[Link]

Page2: BasePage

Elements: Settings,billingTypes, Logoutlink

Methods:

Method1:----gotobillingpage()

 Click on settings
 Click on billing types

Method2: Logout()

Click on logout link

import [Link];
import [Link];
import [Link];
import [Link];

publicclass BasePage {

@FindBy(xpath ="(//div[@class ='popup_menu_arrow'])[1]")


private WebElement settings ;

@FindBy(linkText ="Billing Types")


private WebElement billingTypes;

@FindBy(id ="logoutLink")
private WebElement logoutLink;

public BasePage(WebDriver driver) {


[Link](driver,this);
}

publicvoid gotoBillingPage()
{
[Link]();
[Link]();
}

publicvoid logOut()
{
[Link]();
}

}
Vinay2ml@[Link]

Page3 : createnewBillingpage

Elements: name, createBillingTypebutton

Method1: CreateBilling()

Enter name

Click createBillingType button

import [Link];
import [Link];
import [Link];
import [Link];

publicclass CreateNewBillingPage extends BasePage


{
public CreateNewBillingPage(WebDriver driver) {
super(driver);
[Link](driver, this);
}

@FindBy(id="name")
private WebElement name;

@FindBy(xpath="//input[contains(@value,'Create Billing Type')]")


private WebElement createBillingTypeButton ;

publicvoid createBilling(String billname)


{
[Link](billname);
[Link]();
}

Page4: BillingTypepages

Elements: CreateBillingTypeButton, msg1, msg2, deletelink, ok button(pop-up)

Methods:

Methods1: clickcreateBillingTypes

Click on createBilling Types button


Vinay2ml@[Link]

Method2: verify msg1

Method2: verify msg2

Method4: Delete Billing

1) Click on delete link


2) Click ok on the pop-up

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass BillingTypesPage extends BasePage {

@FindBy(xpath ="//span[text()='Create Billing Type']")


private WebElement createBillingtypesbutton ;

@FindBy(xpath ="//span[@class='successmsg']")
private WebElement amsg ;

@FindBy(xpath ="//a[text()='automation']/../../td[6]/a")
private WebElement deleteLink ;

public BillingTypesPage(WebDriver driver)


{
super(driver);
[Link](driver, this);
}

private WebElement okbutton;

publicvoid clickCreateBillingTypes()
{
[Link]();
}

publicvoid verifymsg(String emsg)


{
String actualmsg =[Link]();
[Link](actualmsg, emsg);

publicvoid deleteBilling(WebDriver driver)


{
[Link]();
[Link]().alert().accept() ;
Vinay2ml@[Link]

}
Testcase_ID :ActiveTime_LoginLogout()

Steps:
 Enter valid username
 Enter valid password
 Enter on login button
 Click on logout link

import [Link];

publicclass testActiveTime_LoginLogout extends SuperTestNG {

@Test
publicvoidtestActiveTime_LoginLogout()
{
LoginPage loginpage = new LoginPage(driver) ;
[Link]("admin", "manager");

BasePage basepage =new BasePage(driver);


[Link]() ;

TestCase_ID: ActiveTime_CreateBilling()
Steps:
Enter valid user name and password
Click on login button
Click on setting and then click on Billing types
click on Create Billing Types
Enter the name ex: Automation and click on create Billing Type
Verify that following success Message displayed
Msg =‛Billing type has been successfully created‛
Click on logout

import [Link];

publicclass testActiveTime_createBilling extends SuperTestNG {

@Test
publicvoidtestActiveTime_createBilling(){
Vinay2ml@[Link]

LoginPage loginpage = new LoginPage(driver) ;


[Link]("admin", "manager");

BillingTypesPage billpage = new BillingTypesPage(driver);

[Link]() ;
[Link]();

CreateNewBillingPage createbill = new CreateNewBillingPage(driver);


[Link]("Automation");

[Link]("Billing type has been successfully created.");

[Link]() ;

}
}

Data Driver Test:

Testing the application with multiple inputs is called as Data driver testing in
order to do this we take the test data from the Excel sheet.

In order to handle the excel sheet we use POI (Poor obfuscation implementation) jar
file provided by Apache which can be downloaded from the following website.

[Link]
Vinay2ml@[Link]

Download the zip file and copy paste the downloaded file into required location and
unzip.

It will create the folder with the following:

Copy only below mentioned 5 jar file into the Jar file folder into the automation
framework.
Vinay2ml@[Link]

Associate all the above selected jar files into the java project.

Basic architecture of Excel with respect to Apache POI files

WorkbookFactory -----------Read ---FileinputStream


Vinay2ml@[Link]

Workbook -----------------write-- outputstream

In Excel Row No and Cellno start with Zero(0).


Ex: Reading data present in the first cell of the Xl sheet1 0 and cell 0.

Ex:

import [Link];
[Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass ExcelDemo {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException
{
String xlpath ="C:/AWS/Automation/excelfiles/[Link]" ;
FileInputStream filein = new FileInputStream(xlpath);
Workbook wb = [Link](filein);
Sheet s1 = [Link]("sheet1");
Row r = [Link](0) ;
Cell c =[Link](0);
String v = [Link]();
[Link](v);

Optimized code:

import [Link];
[Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

publicclass ExcelDemo1 {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException {
Vinay2ml@[Link]

//.(dot) represent the JAVA Path ex: C:/AWS/Automation/


String xlpath = "./excelfiles/[Link]" ;
FileInputStream filein =new FileInputStream(xlpath) ;
Workbook wb =[Link](filein);
Sheet s1 = [Link]("sheet1") ;
String v = [Link](0).getCell(0).getStringCellValue();
[Link](v);

Note:
1) Instead of the specify complete path of the XL file absolute path we can
specify Relative path using which represents the complete path of current JAVA
project.
2) FileInputStream will throw IOException (Checked exception)
Ex:
Exception in thread "main" [Link]:
.\excelfiles\[Link] (The system cannot find the file specified)

3) Create Factory method will throw InvalidFormatException it also(checked


Exception)
Ex: String xlpath = "./excelfiles/[Link]" ;
Exception in thread "main" [Link]: Your
InputStream was neither an OLE2 stream, nor an OOXML stream

4) If sheet name or roll number or cell number is invalid will get


NuLLpointerException.(unchecked Exception)

Ex:String v = [Link](100).getCell(0).getStringCellValue();
Exception in thread "main" [Link]

1) Write a code to count the number of Rows present in the Xl sheet.

import [Link];
[Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

publicclass RowCount {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException
{
Vinay2ml@[Link]

String xlpath ="C:/AWS/Automation/excelfiles/[Link]" ;


FileInputStream filein = new FileInputStream(xlpath);
Workbook wb =[Link](filein);
Sheet s1 = [Link]("sheet1") ;
[Link]([Link]());
}

Note: getLastRowNum() return index of the last Row that is if the 10 rows are
present , it will return 9.

2) Write a script to count the number of cells present in the first Row.

import [Link];
[Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

publicclass CountCellfristRow {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException {
String xlpath = "./excelfiles/[Link]" ;
FileInputStream filein =new FileInputStream(xlpath);
Workbook wb =[Link](filein);
Sheet s1 =[Link]("sheet1");
[Link]([Link](2).getLastCellNum());

Note: getLastCellNum() return the number of cell present in the specified Row and not
the Index.

3) Write a code to print number of cells present in the each row of the excel
sheet.

import [Link];
[Link];
import [Link];

import [Link];
Vinay2ml@[Link]

import [Link];
import [Link];
import [Link];

publicclass CountEachRowCell {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException {
String xlpath = "./excelfiles/[Link]" ;
FileInputStream filein =new FileInputStream(xlpath);
Workbook wb =[Link](filein);
Sheet s = [Link]("sheet1");
int countrow = [Link]();
for(int i =0 ; i<=countrow; i++)
{
[Link]([Link](i).getLastCellNum()) ;
}

4) Write the code to print the content of the xl Sheet.

import [Link];
[Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass PrintContentXL {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException {
String xlpath = "./excelfiles/[Link]" ;
FileInputStream filein = new FileInputStream(xlpath);
Workbook wb =[Link](filein);
Sheet s1 =[Link]("sheet1");
int rowcount = [Link]();
for(int i =0; i<rowcount; i++)
{
Row r = [Link](i) ;
int countcell =[Link]() ;
for(int j=0; j <countcell ;j++)
{
[Link]([Link](j).getStringCellValue()+ " ") ;
Vinay2ml@[Link]

}
[Link](" ");
}

Note: if any row and cell is blank in between then we get NullpointerException , we
should handle it using try catch block.

5) Write data back to Excel Sheet .

In order to store the value in the xl sheet we use SetCellValue() to Save the
XL file use write() method of workbook, which takes FileoutputStream as
argument as show in below

import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

publicclass WritetoExcel {

publicstaticvoid main(String[] args) throws IOException,


InvalidFormatException {
String xlpath = "./excelfiles/[Link]" ;
FileInputStream filein =new FileInputStream(xlpath);
Workbook wb =[Link](filein);
Sheet s = [Link]("sheet1");
//Existing row and cell to write new value
[Link](0).getCell(0).setCellValue("java");

//Existing row and new cell value


[Link](0).createCell(17).setCellValue("Vinay");

[Link](10).createCell(0).setCellValue("Jugga");

FileOutputStream fos = new FileOutputStream(xlpath);


[Link](fos);
}

}
Vinay2ml@[Link]

Generic Methods:

Any Method Which can be used in different projects or called as Generic methods.
Such as handling XL files and handling Database etc.

Any Method which can be used only with in the current project or called as Project
specific method.

Ex: All the methods develop under page object module, ex: createBilling,
DeleteBilling etc.

Steps to Develop Generic Library:


1) Crate package with the name .[Link] under src floder.
2) Crate java class with name [Link] and write the code as shown below.

package [Link];

import [Link];

import [Link];
import [Link];

publicclass Excellib {

publicstaticint getRowCount(String xlpath,String sheetName)


{
try
{
FileInputStream fos = new FileInputStream(xlpath);
Workbook wb = [Link](fos);
int rowcount = [Link](sheetName).getLastRowNum();
return rowcount;
}
catch(Exception e)
{
return -1;
}

publicstaticstring getCellValue(String xlpath,String sheetName, int rownum,


int cellnum)
{
try
{
FileInputStream fos = new FileInputStream(xlpath);
Workbook wb = [Link](fos);
String strvalue =
[Link](sheetName).getRow(rownum).getCell(cellnum).getStringCellValue();
return strvalue;

}
catch(Exception e)
{
Vinay2ml@[Link]

return"";
}
}
}

Common questions

Powered by AI

The 'Select' class in Selenium WebDriver is used to select and deselect options from drop-down lists that are implemented using the HTML <select> tag. It provides methods like 'selectByVisibleText()' to interact with standard list boxes. However, it cannot be used on customized list boxes that don't use the <select> tag, as this results in an 'unexpected tag name Exception'. Instead, customized list boxes are handled using methods like 'sendKeys()' .

In TestNG, a test suite is set up using annotations such as '@BeforeMethod' to perform login before each test, and '@AfterMethod' to perform logout after each test. '@BeforeClass' and '@AfterClass' can initialize and clean up resources before and after all test methods respectively. Tests are annotated with '@Test'. A suite can be executed via an XML file that lists all relevant TestNG classes and defines execution order .

The 'findElements()' method returns a List of WebElements and does not throw an exception if no elements are found, whereas 'findElement()' returns a single WebElement and throws a 'NoSuchElementException' if no elements match. 'findElements()' can return an empty list, while 'findElement()' throws an exception if no elements match .

Dynamic list boxes have content that changes during runtime, often implemented using AJAX. Unlike static list boxes, their options are not predetermined. To handle dynamic list boxes, Selenium's 'Select' class is used in conjunction with explicit waits to ensure elements are loaded before interacting with them, which is critical due to the asynchronous changes in the list content .

TestNG uses a file called 'testng-failed.xml', which is automatically created in the 'test-output' folder after a test run. This file lists all failed test cases, allowing users to easily re-execute only the failed tests by running this XML file as a TestNG suite .

TestNG facilitates parallel test execution by using the 'parallel' attribute in the TestNG XML configuration file. The attribute can be set to 'tests' or 'methods' to enable concurrent execution. Additionally, '@Parameters' are used in test methods to specify conditions like browser choice for execution. This setup reduces the overall test run time by executing multiple tests simultaneously .

Data-driven testing in Selenium using TestNG and Apache POI involves executing test cases using multiple data inputs stored in an Excel sheet. Apache POI is used to read and write data to/from Excel files. This approach allows for extensive test coverage by running the same test with various data sets, enhancing test robustness and reusability. Its advantages include flexibility in handling large data sets and ease of managing test data externally .

The 'isSelected()' method can be used to confirm if a checkbox is selected in Selenium WebDriver. It returns a boolean value. In a script, it is implemented by finding the checkbox element using 'findElement()', then calling 'isSelected()' on that element. For example: If 'chebox1.isSelected()' is true, it prints 'Check box is selected', otherwise 'check box is not selected' .

The 'WorkbookFactory' class in Apache POI is crucial for creating a 'Workbook' instance from a file input stream, regardless of the Excel file format (XLS or XLSX). In a Selenium test script, it's used to read data from Excel by parsing the file into a 'Workbook', accessing sheets, rows, and cells to retrieve test data, enabling data-driven testing .

In Selenium, to select all options in a multi-select list box, a developer uses a loop to iterate over each option and select it individually. There is no direct 'select all' method because the 'Select' class operates on individual selections, reflecting standard HTML form control limitations, hence requiring a scripted iterative approach .

You might also like