Saturday, 29 September 2018

WebDriver Validation Methods - Examples to Practice

WD Validation Methods:
-------------------------------
WebDriver provided following methods to validate webelements
i. isSelected:
ii. isEnabled:
iii. isDisplayed:
iv. size:

i. isSelected():
This method is used to check specified webelement is selected or not,
based on which it will return true/false

Exp: Check box, Radiobutton...etc.,

Syntax:
WebElement.isSelected();


ii. isEnabled():
This method is used to check specified webelement is enabled or not,
based on which it will return true/false

Exp: Pushbutton etc...,
Syntax: WebElement.isEnabled();


***iii. isDisplayed();
This method is very important, is used to check specified webelement displayed or
  not, based on whcich it will return true/false (i.e. visible/invisible webelement)

Exp: Create script to check "Return" webelement visible or not BEFORE
and AFTER clicking on "Multi-City" on www.makemytrip.com home page

WebDriver driver= new FirefoxDriver();
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();

System.out.println("Before selection of Multi-city");
//to check Return field displayed or not
if(driver.findElement(By.id("hp-widget__return")).isDisplayed()){
System.out.println("Return -field is Displayed");
}
else{
System.out.println("Return -field is invisible");
}

//to select "multicity"
driver.findElement(By.xpath("//label[text()='multi-city']")).click();
System.out.println("After selection of Multi-city");
//to check Return field displayed or not
if(driver.findElement(By.id("hp-widget__return")).isDisplayed()){
System.out.println("Return -field is Displayed");
}
else{
System.out.println("Return -field is invisible");
}


iv. Size():
To check specified webelement code availability in a page source we can use
size() method

Syntax:
driver.findElements(By.locator(“locator value”)).size();

Exp: Write script to check “Afrikaans” language link availability in Google
home page before & after click on that link

WebDriver driver= new FirefoxDriver();
driver.get("http://google.co.in");
driver.manage().window().maximize();

System.out.println("Before clicking on Afrikaans link");
//to check Afrikaans link availability
int n=driver.findElements(By.linkText("Afrikaans")).size();
if(n !=0){
System.out.println("Number of Afrikaans links are: "+n);
}
else{
System.out.println("There are no Afrikaans links");
}
//to click on Afrikaans link
driver.findElement(By.linkText("Afrikaans")).click();

//to pause execution
Thread.sleep(3000);

System.out.println("After click on Telugu link");
//to check Afrikaans link availability
n=driver.findElements(By.linkText("Afrikaans")).size();
if(n !=0){
System.out.println("Number of Afrikaans links are: "+n);
}
else{
System.out.println("There are no Afrikaans links");
}

Working on WebTables - Examples to Practice

7. Working with WebTables
------------------------------------
WebTable elements are usually located under “tr” and “td” tags

tr -->is a Table row
number of “tr” tags count equals number of Rows in a Table

td-->table data/cell data
number of “td” tags count equals number of columns in a Table

th -->is a Table header

using "getText()" method we can use to read cell value
Exp: td.getText() will read cell value


Exp: Write script to read specific cell value from webtable

Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://www.w3schools.com/");
driver.manage().window().maximize();

//to click on "Learn HTML"
driver.findElement(By.linkText("Learn HTML")).click();

//to click on "HTML Tables"
driver.findElement(By.linkText("HTML Tables")).click();

//to read cell data
String cellData=driver.findElement(By.xpath("//table[@id='customers']/tbody/tr[3]/td[2]")).getText();
System.out.println(cellData);


Exp: Write script to read all the cell values from webtable

Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://www.w3schools.com/");
driver.manage().window().maximize();

//to click on "Learn HTML"
driver.findElement(By.linkText("Learn HTML")).click();

//to click on "HTML Tables"
driver.findElement(By.linkText("HTML Tables")).click();

//create reference object for WebTable
WebElement myTable=driver.findElement(By.id("customers"));

//to get all the "td" tags within the table
List tds=myTable.findElements(By.tagName("td"));
System.out.println("Number of td tags are: "+tds.size());
//to read each td/cell data
for(WebElement td: tds){
System.out.println(td.getText());
}


Ex: Write script to find number of Rows, number of columns in each row, and read cell value from Webtable

Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://www.w3schools.com/");
driver.manage().window().maximize();

//to click on "Learn HTML"
driver.findElement(By.linkText("Learn HTML")).click();

//to click on "HTML Tables"
driver.findElement(By.linkText("HTML Tables")).click();

//create reference object for WebTable
WebElement myTable=driver.findElement(By.id("customers"));

//to find number of Rows
List t_rows=myTable.findElements(By.tagName("tr"));
System.out.println("Number of Rows are: "+t_rows.size());

//to find each row number of td tags
for(WebElement t_row: t_rows){
List tds= t_row.findElements(By.tagName("td"));
System.out.println("Number of td tags are: "+tds.size());
for(WebElement td: tds){
System.out.println(td.getText());
}
System.out.println("***************************");
}

Thursday, 27 September 2018

Working on PushButtons and WebLinks - Examples to Practice

5. Working on Pushbuttons
---------------------------------
we can use click() command to click on pushbutton
we can use isEnabled() command to check object is enabled/disabled on a page

Exp:  Write script to click on "Sign up" button when that object is
enabled and also read name and visibletext of the object

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://facebook.com");
driver.manage().window().maximize();

//create reference object for "Sign up"
WebElement signupObj=driver.findElement(By.id("u_0_11"));

//to read visibletext of object
String btnText=signupObj.getText();
System.out.println("Object visibletext is: "+btnText);

//to read name attribute of object
String btnName=signupObj.getAttribute("name");
System.out.println("Object name is: "+btnName);

//to check object is enabled or not
if (signupObj.isEnabled()){
System.out.println("Object is enabled");
signupObj.click();
}
else{
System.out.println("Object is disabled");
}


6. Working with Links
----------------------------
In general links tagname will be “a” (anchor tag)
To address links we can use "linkText" or "partialLinkText"
-click(): command used to click on the links
-getText(): command used to read innertext property value of the link

Exp:  Write script to find number of links available on www.facebook.com home page and print those link names

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");

List  links=driver.findElements(By.tagName("a"));
System.out.println("Number of links are: "+links.size());
//to print each link name
for(WebElement link: links){
System.out.println(link.getText());
}

Exp: Write script to find and click on "REGISTER" link from NewTours home page
String myLink="Register";
WebDriver driver= new FirefoxDriver();
driver.get("http://newtours.demoaut.com");
driver.manage().window().maximize();

List links=driver.findElements(By.tagName("a"));


//to read each link visibletext
for(WebElement link: links){
if(link.getText().equalsIgnoreCase(myLink)){
link.click();
System.out.println("specified link exist");
break;
}
}
Exp: Write script to find number of language links in www.google.co.in
WebDriver driver= new FirefoxDriver();
driver.get("http://google.co.in");
driver.manage().window().maximize();


//create reference object for parent object of language links
WebElement myLanguages=driver.findElement(By.id("SIvCob"));
//to find number of language links in a page
List links=myLanguages.findElements(By.tagName("a"));
System.out.println("Number of language links are: "+links.size());

//to read each link visibletext
for(WebElement link: links){
System.out.println(link.getText());
}

Wednesday, 26 September 2018

Synchronization in WebDriver

The time mapping between Script Execution on WebDriver and Eelapsed
time of AUT is called Synchronization

Elapsed time means, time taken by the application to complete specific transaction/operation

Below scenarios are some of the examples where synchronization is applied:
-during application launching time
-when application is performing back end transactions
such as Insert, update and Delete
-when application is loading next page (i.e. Page load time)
-to reach status bar 100% (i.e. uploading/downloading files)


Synchronization options:
-----------------------
There are 2 ways to synchronize test execution

1. Unconditional based Synchronization: Using "Thread" class we can pause execution to fixed time,
irrespective of application process

Syntax:
Thread.sleep(time in milliseconds);

2. Conditional based Synchronization: Based on particular element (i.e. driver.findElement) or elements
(i.e. driver.findElements) availability we can pause execution
In webdriver we have 3 types of options to synchronize test execution
a. Implicit wait:
b. Explicit wait:
c. Fluent wait:


a. Implicit wait: Using this option, we can pause execution to specified amount of time
(i.e. 30 sec) when any webelement is not able to identify on a page during runtime

Syntax:

driver.manage().timeouts().implicitlyWait(time, TimeUnit parameter);
Exp:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Exp: Write script to select "Hyderbad-MGBS" in "http://www.apsrtconline.in/oprs-web" using implicit wait

WebDriver driver= new FirefoxDriver();
driver.get("http://www.apsrtconline.in/oprs-web/");
driver.manage().window().maximize();
//implicitlywait (This applies to all the elements in this script, hence this is widely used)
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

//to enter "HYD"
driver.findElement(By.id("fromPlaceName")).sendKeys("HYD");

//to pause execution
//Thread.sleep(3000);


//to select "HYDERABAD MGBS"
driver.findElement(By.linkText("HYDERABAD MGBS")).click();





b. Explicit wait: To pause execution at particular position based on presence
of webelement in DOM(i.e. to wait when webelement code not available in HTML page)

Syntax:
Wait obj=new WebDriverWait(driver, 30);
obj.until(ExpectedConditions.presenceOFElementLocated(By.id("id value of element"));

Exp: Write Explicit wait to pause execution based on "Password" webelement presence

Wait wt= new WebDriverWait(driver, 30);
wt.until(ExpectedConditions.presenceOfElementLocated(By.id("Passwd")));

Exp: Write script to select "Hyderbad-MGBS" in "http://www.apsrtconline.in/oprs-web" using explicit wait

WebDriver driver= new FirefoxDriver();
driver.get("http://www.apsrtconline.in/oprs-web/");
driver.manage().window().maximize();

//to enter "HYD"
driver.findElement(By.id("fromPlaceName")).sendKeys("HYD");

//to pause execution
//Thread.sleep(3000);

//to pause execution based on "HYDERABAD MGBS" link availability using Explicitwait
//this applies to the specific element only unlike implicitwait
Wait wt= new WebDriverWait(driver, 30);
wt.until(ExpectedConditions.presenceOfElementLocated(By.linkText("HYDERABAD MGBS")));

//to select "HYDERABAD MGBS"
driver.findElement(By.linkText("HYDERABAD MGBS")).click();



c. Fluent Wait: Using this option we can specify specified amount of time to pause execution
when webelement is not found to operate, it will try to find webelement repeatadly
on a page(DOM) based on given time paramter (i.e. polling time)

Syntax:
FluentWait wt = new FluentWait(driver).withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);


Exp: WebDriver driver= new FirefoxDriver();
driver.get("http://www.apsrtconline.in/oprs-web/");
driver.manage().window().maximize();

//implicitlywait
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

//to enter "HYD"
driver.findElement(By.id("fromPlaceName")).sendKeys("HYD");

//to pause execution
//Thread.sleep(3000);

//to pause execution based on "HYDERABAD MGBS" link availability
FluentWait wt = new FluentWait(driver).withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

wt.until(ExpectedConditions.presenceOfElementLocated(By.linkText("HYDERABAD MGBS")));

//to select "HYDERABAD MGBS"
driver.findElement(By.linkText("HYDERABAD MGBS")).click();
}


Exp: Write script to validate login functionality in Gmail application with valid data


script:
WebDriver driver= new FirefoxDriver();
driver.get("http://gmail.com");
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.findElement(By.id("identifierId")).sendKeys("seleniumuser15");
driver.findElement(By.xpath("//span[text()='Next']")).click();

//to pause execution
Wait wt= new WebDriverWait(driver, 30);
wt.until(ExpectedConditions.presenceOfElementLocated(By.name("password")));

driver.findElement(By.name("password")).sendKeys("Mercury9");
driver.findElement(By.xpath("//span[text()='Next']")).click();

Thread.sleep(3000);

String pgTitle= driver.getTitle();
if (pgTitle.contains("seleniumuser15")){
System.out.println("succesful login operation");
}
else{
System.out.println("unsuccessful login operation");
}


CASESTUDY:  Synchronization in WebDriver:  We need to wait for elements
-to be present -->in DOM for any webelement(ImplicitWait)
-to be available -->in DOM for specific webelement (ExplicitWait)
-to be clickable -->FluentWait

Tuesday, 25 September 2018

Working on CheckBoxes and RadioButtons - Examples to Practice

3. Working on Checkboxes:
----------------------------------
We use click() command to set "ON/OFF" for a checkbox
isSelected() command used to check that checkbox is set ON/OFF, based on that
it will return true/false

Exp: Write script to select checkbox in "https://login.salesforce.com" login page

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://login.salesforce.com");

driver.findElement(By.id("rememberUn")).click();

Exp: Write script to uncheck 2nd checkbox in "http://echoecho.com/htmlforms09.htm" page

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://echoecho.com/htmlforms09.htm");
driver.manage().window().maximize();

//to uncheck 2nd checkbox
driver.findElement(By.xpath("html/body/div[2]/table[9]/tbody/tr/td[4]/table/tbody/tr/td/
div/span/form/table[1]/tbody/tr/td/table/tbody/tr[2]/td[3]/input[2]")).click();




Exp: Write script to select the checkboxes that are unselected on "http://echoecho.com/htmlforms09.htm" page

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.echoecho.com/htmlforms09.htm");

//to find number of checkboxes in a page
List chks= driver.findElements(By.name("Checkbox"));

System.out.println("number of checkboxes are :"+chks.size());
//to click on checkbox which are not selected
for(WebElement chk:chks){
if(chk.isSelected()==false){
chk.click();
}
}


4. Working on Radiobuttons:
-----------------------------------
We can use click() command to operate radiobutton

Exp: Write script to click on each radio button in facebook home page and to print name of each radiobutton

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");

//to find number of radiobuttons
List radios=driver.findElements(By.className("_58mt"));
System.out.println("number of radiobuttons are :"+radios.size());

//to select radiobuttons one after one
for (WebElement radio: radios){
//to read radiobutton name
System.out.println(radio.getText());
radio.click();
Thread.sleep(3000);
}








Saturday, 22 September 2018

Working on EditBox and Dropdowns - Examples to Practice


Examples to Practice
--------------------------

1. Edit box/Text box:
In general, we use id or name as Locator to address Edit box/Text box
To work on Edit box we can use following commands
i. click(): to focus on specified edit box
ii.sendKeys(): to enter data into the edit box
iii. getAttribute("value"): to read data from the Edit box
iv. clear(): to clear the data from the edit box

Exp: Create script to automate following scenario:
open www.facebook.com in FF browser
focus on "Email" edit box
enter value "InsightQ" in "Email" edit box
read data from "Email" edit box
verify entered value matching with existing value in edit box
clear data in edit box

Script:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");

String uid="InsightQ";

//creating reference object for webelement
WebElement we= driver.findElement(By.id("email"));
//to focus on webelement
we.click();
//to enter data
we.sendKeys(uid);
//to read data from edit box
String userid=we.getAttribute("value");
//to compare the values
if (userid.equals(uid)){
System.out.println("entered value existing");
}else{
System.out.println("values are mistaching");
}
//to clear the data
we.clear();

NOTES:  Reference/Instance object is used for a webelement in the script
for reusability of the webelement

Syntax:
WebElement obj= driver.findElement(By.Locator("locator value"));

Exp:
WebElement myObj= driver.findElement(By.id("Passwd"));
---------------------------------------------------------------------------------------------

2. Dropdowns:
Also called a list box/combobox
there are 2 types of dropdowns
i. Auto-suggested Dropdowns:
ii. Static Dropdowns:

i. Auto-suggested Dropdowns:
User can enter data as well as select value from search result
we can use click() method to operate this dropdown
sendKeys() method to enter data

Exp: Create script to automate following scenario:
open http://spicejet.com in FF browser
click on "From" dropdown box
select "GOA"

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://spicejet.com");

driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
driver.findElement(By.linkText("Goa (GOI)")).click();
---------------------------------------------------------------------------------------------

Exp: Create script to automate following scenario:
open http://www.apsrtconline.in/oprs-web/ in FF browser
enter value "Hyd" in "From" dropdown box
click on "HYDERABAD MGBS"

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://www.apsrtconline.in/oprs-web/");
driver.manage().window().maximize();

//to enter value in "From" object
driver.findElement(By.name("fromPlaceName")).sendKeys("Hyd");

//to pause execution fixed time
Thread.sleep(3000);

//to select "HYDERABAD MGBS"
driver.findElement(By.linkText("HYDERABAD MGBS")).click();

---------------------------------------------------------------------------------------------

ii. **Static Dropdowns:
Under this, the values are fixed,
Static dropdown tagname will be "select"
To handle this type of webelements, WD providing "Select" class

Syntax:{for type-casting to the static dropdown}

Select obj= new Select(driver.findElement(By.locator("locator value"));

using following commands we can select value in Static dropdowns
i. obj.selectByVisibleText();
using this option we can select option in dropdown
using visibletext/value which is displayed in dropdown

ii. obj.selectByValue
using this option we can select value in dropdown
based on "value" attribute of option

iii. obj.selectByIndex();
sometimes we can also use index to select option
in dropdown (NOTE:  index starts with 0,1, 2,....)

iv. getOptions():
using this method we can get all the options information
from static dropdown

v. getText():
using this method we can read visibletext of options
from static dropdown

vi. **getFirstSelectedOption():
using this command we can read selected value from dropdown
Syntax:
obj.getFirstSelectedOption();


Exp:  Create script to automate following scenario:
open "http://facebook.com" in FF browser
select "Sept" using visible text
select "Apr" using value
select "Dec" using index

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://facebook.com");
driver.manage().window().maximize();

//type casting Select class
Select myList= new Select(driver.findElement(By.id("month")));

//to select "Sept" using visible text
myList.selectByVisibleText("Sept");

Thread.sleep(3000);

//to select "Apr" using value
myList.selectByValue("4");

Thread.sleep(3000);
//to select "Dec" using index
myList.selectByIndex(12);

---------------------------------------------------------------------------------------------

Exp:  Write script to select "Jan" in "Month" dropdown if it is not selected in that dropdown
Exp:  Create script to automate following scenario:
open "http://facebook.com" in FF browser
read value from the dropdown
select "Jan" if its not selected

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://facebook.com");
driver.manage().window().maximize();

//type caste dropdown with select class
Select myList= new Select(driver.findElement(By.id("month")));
//read selected value from dropdown
WebElement option= myList.getFirstSelectedOption();
String month=option.getText();
System.out.println(month);
//if it is not selected
if (month.equals("Jan")){
System.out.println("Jan-month already selected");
}
else{
//to select "Jan"
myList.selectByVisibleText("Jan");
System.out.println("Month slected by WD");
}


---------------------------------------------------------------------------------------------

NOTE: To find number of values in dropdown we can use getOptions() command
NOTE: To read values from dropdown we use getText()

Exp:  Create script to automate following scenario:
open "http://spicejet.com" in FF browser
select first item from the currency dropdown
select "INR" using value
select "AED" using visibletext
find number values under currency dropdown
print all currency values one by one


Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://spicejet.com");
driver.manage().window().maximize();

//type-casting to "Currency" dropdown
Select myDropDown=new Select(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")));


//to select 1st item
myDropDown.selectByIndex(0);

//to pause the execution
Thread.sleep(2000);

//to select item which have the value as "INR"
myDropDown.selectByValue("INR");

Thread.sleep(2000);

//to select item by visibletext "AED"
myDropDown.selectByVisibleText("AED");

//to find number of values
List items= myDropDown.getOptions();

System.out.println("Number of values are: "+items.size());

//to print those values
for(WebElement item: items){
System.out.println(item.getText());
}
---------------------------------------------------------------------------------------------

Exp:
Create script to automate following scenario:
open "www.newtours.demoaut.com"
click on "Register" link
select "INDIA" using visibleText in "Country" dropdown
select "ALBANIA" using index
select "INDIA" using value
find number of values in that dropdown
print all the values


Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://newtours.demoaut.com");

//to clickon Register link
driver.findElement(By.linkText("REGISTER")).click();

//create instance object for Country weblist (i.e. casting)
Select we= new Select(driver.findElement(By.name("country")));
//select "INDIA" using visibleText
we.selectByVisibleText("INDIA");
//to pause execution
Thread.sleep(2000);
//select "ALBANIA" using index
we.selectByIndex(0);
Thread.sleep(2000);
//select "INDIA" using value
we.selectByValue("92");
//find number of values in that dropdown
List options=we.getOptions();
System.out.println("number of values are: "+options.size());
//print all the values
for(WebElement option: options){
System.out.println(option.getText());
}

---------------------------------------------------------------------------------------------

Exp:
Create script to automate following scenario:
open "http://spicejet.com"
select first item from currency dropdown using index
select second item using visibleText
select last item using value
find number of values in that dropdown
print all the values

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://spicejet.com");

Select myList= new Select(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")));

//to select 1st option

myList.selectByIndex(0);

Thread.sleep(2000);
//to select 2nd option using visibletext

myList.selectByVisibleText("AED");
Thread.sleep(2000);
//to select last option using value
myList.selectByValue("USD");

//to find number of values in dropdown
List options= myList.getOptions();

System.out.println("no of options are: "+options.size());
for(WebElement x: options){
System.out.println(x.getText());
}

---------------------------------------------------------------------------------------------

Exp:
Create script to automate following scenario:
open "http://newtours.demoaut.com"
click on Register link
find number values under the country dropdown
check if "INDIA123" exist in country dropdown

Script:
WebDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://newtours.demoaut.com");

driver.findElement(By.linkText("REGISTER")).click();

Select myList= new Select(driver.findElement(By.name("country")));
String myCountry= "INDIA123";
//to find number of values in list box
List options=myList.getOptions();

boolean myStatus= false;
for(WebElement option:options ){
String myVal=option.getText();
if(myVal.equals(myCountry)){
myList.selectByVisibleText(myCountry);
myStatus=true;
break;
}
}

if (myStatus== false){
System.out.println(myCountry+" value not exist");

}

---------------------------------------------------------------------------------------------
Exp:
Create script to automate following scenario:
open "http://facebook.com"
read values from month dropdown
check if "Dec" is selected if not select "Dec"

Script:
WebDriver driver= new FirefoxDriver();
driver.get("http://facebook.com");
driver.manage().window().maximize();

Select birMonth=new Select(driver.findElement(By.name("birthday_month")));

//to read selected option from dropdown
WebElement option=birMonth.getFirstSelectedOption();
String x=option.getText();
System.out.println(x);
if(x.equals("Dec")){
System.out.println("Dec- already selected");
}
else{
//to select "Dec" using visibletext
birMonth.selectByVisibleText("Dec");
}

Wednesday, 12 September 2018

Interview Questions on Java Concepts on Selenium

Common interview questions on Java program usage in Selenium

Exp-1: Write program to display fibonacci series of numbers up to 100
0,1,1,2,3,5,8,13,21....each number is equals to the sum of the preceding two numbers,
this can start with zero or one

Script:
int a, b, c;
a= 0;
b= 1;

System.out.println(a);
System.out.println(b);
c= a+b;
while( c <= 100){
System.out.println(c);

a= b;
b= c;
c= a+b;
}

Exp-2: Write program to display Prime numbers between 1 to 20
A Prime number can be divided evenly only by 1 or itself

Script:
int cnt;
for (int n=1; n <= 20; n++){
cnt=0;
for(int i=1; i<= 20; i++){
if( n%i==0){
cnt++;
}

}
if(cnt==2){
System.out.println(n);
}
}

Exp-3: Write program to find number of occurrences of "s" in "SeleniumCourses"

String myVal="SeleniumCourses";
char myChar='s';
int n=0;
for(int i=0; i <= myVal.length()-1; i++){
if(myVal.charAt(i)== myChar){
n=n+1;
//n++;
}
}

System.out.println("Occurence of S in main string is: "+n);

}


Exp-4: Write program to find index of "s" in "SeleniumCourses"

String myVal="SeleniumCourses";

System.out.println(myVal.indexOf("s")); //5


Exp-5: Write program to find number of occurence of "s" in main string and also print each "s" position

String myVal="SeleniumCourses";


char myChar='s';
int n=0;
for(int i=0; i <= myVal.length()-1; i++){
if(myVal.charAt(i)== myChar){
n=n+1;
System.out.println("S-position is: "+i);
}
}

System.out.println("Occurence of S in main string is: "+n);


Exp-6: Write program to reverse the given string

String myVal="SeleniumCourses";

String str="";
for(int i=myVal.length()-1; i >=0; i--){
str=str+myVal.charAt(i);

}
System.out.println(str);


Exp-7: Write program to check given string is a palindrome or not
(reading the same backward as forward)

ex: refer

String myVal="refer";

String str="";
for(int i=myVal.length()-1; i >=0; i--){
str=str+myVal.charAt(i);

}

if(myVal.equals(str)){
System.out.println("it is a palindrome");
}
else{
System.out.println("it is not a palindrome");
}
---------------------------------------------------------------------------------------------------------

Wednesday, 29 August 2018

Java Concepts -4

Loop Statements/Iterative statements:
-------------------------------------
Loop Statements/Iterative statements are used to execute some portion of the script multiple times/iterations
a. While Loop:
b. Do while Loop:
c. For loop:

a. While Loop:
It will allow script to execute multiple iterations until given condition is true

Syntax:
while (condition){
----------
----------//Repeatable statements
}
Exp:
int n=1;
while (n <= 5){
System.out.println(n);
n++;
}

b. Do While Loop:
It will allow atleast one time to execute the block of statements irrespective of condition true/false

Syntax:
do{
    ----------
    ----------//statements
[break]
}


NOTE: [break] is used to terminate the iterations

Exp:
int n=1;

do {
System.out.println(n);
n++;
    }while (n <= 5);


Ex:
int n=1;

do {
System.out.println(n);
if(n==3){
break;
}
n++;
}while (n <= 5);

ex:
int n=6;
do {
System.out.println(n);
n++;
}while (n <= 5);

c. For Loop:
For Loop is used to execute a block of statement fixed number times/itersations

Syntax:
for(initialization; condition; increment/decrement){
------------
-----------//Repeatable statements
[break]
}

Exp:
for(int i=1; i <= 5; i++){
System.out.println(i);
  }


Array Declaration:
----------------------
Array is used to store multiple values with same data types

Syntax:
datatype[] array_name= new datatype[size];

size--> number of values to store
array index starts with zero
to find number of values in an Array we can use array.length

Exp: Create an array to store 3 values

//Array Declaration
String[] myCars= new String[3];
//to assign values
myCars[0]="Audi";
myCars[1]="Benz";
myCars[2]="BMW";

//to find size of an array
System.out.println("Number of values are: "+myCars.length);

//to read values from array using index
System.out.println(myCars[0]);
System.out.println(myCars[1]);
System.out.println(myCars[2]);

System.out.println("*******************");
//to read values from array using for loop
for(int i=0; i <= myCars.length-1; i++){
System.out.println(myCars[i]);

For-each:
Used to read each value from an array/collections

Syntax:
for( datatype variableName: array/collectionname)

//to read values from array using For -each
for(String myCar: myCars)
{
System.out.println(myCar);

}


ArrayList/Dynamic Array:
--------------------------------
When we don't know how many values to store in an Array we can use an ArrayList
Syntax:
ArrayList arrayname= new ArrayList();

//to assign values
Syntax:
arrayname.add(value);

//to find size of an ArrayList we can use ArrayList.size();

Exp: Create ArrayList to assign 3 string values

// ArrayList Declaration
ArrayList myCars= new ArrayList();

//to assign values
myCars.add("Audi");
myCars.add("Benz");
myCars.add("BMW");

//to find number of values
System.out.println("Number of values are: "+myCars.size());

//to read values from an arrayList using For each
for(String myCar: myCars){
System.out.println(myCar);
}


Sunday, 26 August 2018

Java Concepts-3

Java concepts-3
---------------
1. Comparative operators
< -less than
> -greater than
<= less than or equals
>= greaterthan or equals
AND or &&
OR or ||
NOT EQULS TO or !=
.equals() or ==
2. Conditinal statements:
To execute particular block of statement based on given condition true/false
i. If condition
ii. else if condition
iii. Nested if
iv. switch case

i. if Condition:
To execute particular block of statement when given expression is true

Syntax:
if (condition){
------
------//statements
}

ex:
int a= 10;
int b= 20;

if (a < b){
System.out.println("a- is smaller than b");
}





ii. else if condition:
using Else If we can execute different block of statements based on given expression/condition is true or false

syntax:
if (condition)
{
-----------
-----------//statements
}
else
{
-----------
-----------//statements
}

Exp: Write program to find smaller value in given 2 numbers
script:
int a= 30;
int b= 20;


if (a < b){
System.out.println("a- is smaller than b");
}
else{
System.out.println("b-is smaller than a");
}




3. Nested if:
To check more than one condition in a block of statement

Syntax:
if (condition-1){
----------------
----------------//Statements-1
}
else if (condition-2){
-------------
-------------//statements-2
}
else{
-------------
-------------//statements-3
}


Exp: write program to find smaller value in given 3 numbers
script:
int a= 30;
int b= 20;
int c= 10;


if ((a < b) && (a < c)){
System.out.println("smaller value is: "+a);
}
else if (b < c){
System.out.println("smaller value is: "+b);
}
else{
System.out.println("Smaller value is: "+c);
}



Exp: write program to find student grade based on given marks
Script:
int stMarks;
String stGrade;
System.out.println("Enter student marks");
//to read student marks from console
Scanner sc= new Scanner(System.in);
stMarks= sc.nextInt();

if (stMarks >= 90){
stGrade="A";
}
else if (stMarks >= 80){
stGrade ="B";
}
else if(stMarks >= 70){
stGrade ="C";
}
else{
stGrade ="D";
}

System.out.println("Student marks are: "+stMarks);
System.out.println("Student Grade is: "+stGrade);


4. Switch statement:
It is similar to nested if, but it will increase reliability of the script

Syntax:
switch(expression)
{
case (condition-1):
-------
-------//statements-1
break;
case (condition-2):
--------
--------//statements-2
break;
case (condition-3):
--------
--------//statements-3
break;
default:
--------
--------//statements-4
}


Exp: Write program to display color name based on given character from "RGB"
script:
System.out.println("Enter any one character from -RGB");
Scanner sc= new Scanner(System.in);
String myColor=sc.nextLine();
switch(myColor.toUpperCase()){
case "R":
System.out.println("Your choice is: RED");
break;
case "G":
System.out.println("Your choice is: GREEN");
break;
case "B":
System.out.println("Your choice is: BLUE");
break;
default:
System.out.println("Invalid entity");
}

========================================================================

Saturday, 25 August 2018

Multiple Browsers on Selenium

Working on Different Browsers
-------------------------
Selenium WD library provided individual classes to interact with different browser

Exp:  FirefoxDriver(), ChromeDriver(), InternetExplorerDriver()...etc

1. Working on Chrome Browser:
-----------------------------
To work on Chrome browser, we need to run Chromedriver server and
need to create object for ChromeDriver() class

Procedure:
Step 1: Download Chromedriver server
Extract zip file into working folder

Step 2: Provide Chromedriver server path into script to Run chromedriver server

Syntax:
System.setProperty(key, path of server);

Exp:
System.setProperty("webdriver.chrome.driver", "E:\\SeleniumResource\\chromedriver.exe");

Step 3: Create object for ChromeDriver() class

Syntax:
WebDriver obj= new ChromeDriver();

Exp:
Write script to perform login operation in Sales Force application using chrome browser

/*Exercise:
  Launch Chrome Browser
  Open ("http://Salesforce.com")
          Maximize the browser window
  Insert Username
  Insert Password
  Click on Login Button
  */

//To launch Chrome browser
System.setProperty("webdriver.chrome.driver", "E:\\SeleniumResource\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Insert Username
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Insert Password
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To click on Login Button
driver.findElement(By.xpath("//input[@id='Login']")).click();


2. Working on IE Browser
------------------------
To work on IE browser, we need to run IEDriver server and
need to create object for InternetExplorerDriver() class

Procedure:
Step 1: Download IEdriver server
Extract zip file into working folder

Step 2: Provide IEDriver server path into script to Run IE driver server

Syntax:
System.setProperty(key, server path);

Exp:
System.setProperty("webdriver.ie.driver", "E:\\SeleniumResource\\IEDriverServer.exe");

Step 3: Create object for InternetExplorerDriver() class

Syntax:
WebDriver obj= new InternetExplorerDriver();

NOTE:
Set IE browser zoom level to 100%
Set all the 4 zones security settings either ON/OFF

Exp:
/*Exercise:
  Launch IE Browser
  Open ("http://Salesforce.com")
          Maximize the browser window
  Insert Username
  Insert Password
  Click on Login Button
  */

//To launch IE browser
System.setProperty("webdriver.ie.driver", "E:\\SeleniumResource\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Insert Username
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Insert Password
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To click on Login Button
driver.findElement(By.xpath("//input[@id='Login']")).click();

3. Working on Latest version of FF browser
------------------------------------------

NOTE:
We Must use WD 3.0 Jar Files and above verions to support Latest FF Browser

Step 1:
Download geckodriver server
url:https://github.com/mozilla/geckodriver/releases
Extract zip file

Step 2: Provide geckoDriver server path into script to Run geckodriver server

Syntax:
System.setProperty(key, server path);

Exp:
System.setProperty("webdriver.gecko.driver", "E:\\SeleniumResource\\geckodriver.exe");

Step 3: Create object for FirefoxDriver() class

Syntax:
WebDriver obj= new FirefoxDriver();

Exp:
/*Exercise:
  Launch Gheko Browser
  Open ("http://Salesforce.com")
        Maximize the browser window
  Insert Username
  Insert Password
  Click on Login Button
  */

//To launch Latest Firefox browser
System.setProperty("webdriver.gecko.driver", "E:\\SeleniumResource\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Insert Username
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Insert Password
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To click on Login Button
driver.findElement(By.xpath("//input[@id='Login']")).click();










Thursday, 16 August 2018

Locators in WebDriver-Very Imp

Locators
----------
Addressing Webelements in WebDriver

WD will identify webelements in a page using locator values
Locators are the html propeties/attributes values of a webelement

Syntax:
driver.findElement(By.LocatorName("Locator value"));


WD Supports 8 types of locators:
1. id
2. name
3. className
4. tagName
5. linkText
6. partialLinkText
7. xpath
8. cssSelector

1. id:
It is most commonly used locator to address webelement
Syntax:
driver.findElement(By.id(id value));

NOTE:
i. click():
Click method is used to perform mouse click on specifed webElement
Syntax:
webelement.click();

ii. sendKeys():
SendKeys method is used to enter data in input objects
Syntax:
webelement.sendKeys(data);

/*Exercise:
  Launch FireFox Browser
  Open salesforce login Page
        Maximize the browser window
  Enter Username
  Enter Password
  Click on Login Button
  Close browser*/

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To enter Username (Invalid Username)
driver.findElement(By.id("username")).sendKeys("SeleniumClass");
//To enter Password (Invalid Password)
driver.findElement(By.id("password")).sendKeys("Password123");
//To click on Login Button
driver.findElement(By.id("Login")).click();
//To close browser
driver.close();


2. name:
Name is also used as a locator to address webelements
Syntax:
driver.findElement(By.name(name value));

/*Exercise:
  Launch FireFox Browser
  Open ("http://newtours.demoaut.com")
        Maximize the browser window
  Enter Username
  Enter Password
  Click on Login Button
  Close browser*/a

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://newtours.demoaut.com");
//To maximize the browser window
driver.manage().window().maximize();
//To enter Username (Valid Username)
driver.findElement(By.name("userName")).sendKeys("mercury");
//To enter Password (Valid Password)
driver.findElement(By.name("password")).sendKeys("mercury");
//To click on Login Button
driver.findElement(By.name("login")).click();
//To close browser
driver.close();


3. className:
className is also used as a locator to address webelements
However, className may not be unique to identify webelements
Syntax:
driver.findElement(By.className(className value));

/*Exercise:
  Launch FireFox Browser
  Open ("http://facebook.com")
        Maximize the browser window
  Enter value in password edit box using "className" as a locator*/
 

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To enter value in password edit box
driver.findElement(By.className("inputtext")).sendKeys("Password");

NOTE:   It will enter value in Email edit box because className"inputtext" not unique,
Email edit box className is also "inputtext" Plz check using Firebug
If similar attribute values exist for webelements on a page,  WD will identify fist webelement from
the root tag, in this case, Email edit box is the first element from the root tag


4. linkText:
Used to locate Hyperlinks on a webpage
Hyperlinks tab will always starts with "a" (Anchor tag)
Syntax:
driver.findElement(By.linkText(visible text of link));

/*Exercise:
  Launch FireFox Browser
  Open ("http://facebook.com")
        Maximize the browser window
  Click on "forgotten account?" using linkText locator*/
 

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To click on "forgotten account" link
driver.findElement(By.linkText("Forgotten account?")).click();



5. partialLinkText():
this locator also used to address hyperlinks

syntax:
driver.findElement(By.partialLinkText(partial visible text of link));

/*Exercise:
  Launch FireFox Browser
  Open ("http://facebook.com")
        Maximize the browser window
  Click on "account?" link using partialLinkText locator*/
 

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To click on link
driver.findElement(By.partialLinkText(" account?")).click();

NOTE:
In general, partialLinkText locator is preferred for dynamic links that constantly change

Exp: 
Your order no. 110150 (the number may change time to time)

6. tagName:
This locator is used to address similar type of objects on a page
Syntax:
driver.findElements(By.tagname(value));


7. xpath:
xpath ("x" stands for XML, extendable markup language)
using expath we can address webelements based on hierarchy of tag names in a page

In General, xpath is used when a webelement doesnt have any proper attribute values,
so as cssSelector

Finding xpath on a webpage:
i. Using "firepath"
firepath is an add-on to firefox browser
download and install firepath from firefox browser
once installed, right click on any element on the webpage
click on "Inspect in Firepath"
you will be able to see xpath correctly

NOTE:  Precondition for firepath, Ensure Firebug is already installed in your machine
       in order for firth path to work

There are two types of xpath:
a. Absolute xpath:
b. Relative xpath:

a. Absolute xpath:
addressing webelement from root tag in a page
absolute xpath can be prefixed with "/"

Exp:  Html code in a webpage

html...
header
body
div...
input...
li...
li...
input...
input id="abcd"

Absolute xpath:
/html/body/input/li[2]/input[2]

Exp:
Find Absolute xpath for "Email" edit box on yahoomail homepage

Manually written xpath:     /html/body/div[2]/div/div/form/div/input
or
Firepath Generated xpath:    html/body/div[2]/div[1]/div[1]/form/div/input

Finding Absolute xpath for a webelement using Firepath

Right click on any element
Click on "Inspect in FirePath"
Ensure "Generate Absolute Xpath" is cheked under FirePath Dropdown
Absolute xpath is generated successfully

NOTE:  Checked "Generate Absolute Xpath" option is used for "Absolute Xpath"
     

Exp:
Find Absolute xpath for "Next" button on yahoomail homepage

Manually written xpath:     /html/body/div[2]/div/div/form/input[3]
or
Firepath Generated xpath:    html/body/div[2]/div[1]/div[1]/form/input[3]


Exp:
Find absolute xpath for "sign in" object in www.amazon.in

Manually written xpath:     /html/body/div/div[3]/div/div/div/div[3]/div/a/span
or
Firepath Generated xpath:    html/body/div[1]/div[3]/div/div[1]/div/div[2]/div[1]/a/span

NOTE:  The Absolute xpath in above example has changed between Manually written and Firepath generated
that is becuase there is two days difference between manually written xpath and
Firepath generated xpath, amazon has made some changes on the webpage in last two days. 
Everytime, there is a change on webpage, the absolute xpath changes,
this is the reason why absolute xpath is NOT a preferred locator

Exp:
Find absolute xpath for "Next" button in Gmail-home page using Firepath

Firepath Generated xpath:    html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/content/span


b. Relative xpath:
Relative xpath is prefered more than Absolute xpath
Relative xpath is a combination of tagname and anyone of the
attribute value of a webelement

Syntax:
//tagname[@attributename='value']

Exp: Write relative xpath for "Email" edit box in Gmail-home page
//input[@id='identifierId']
or
//input[@name='identifier']
or
//input[@type='email']

Different options in Relative xpath:

i. using "*" in Relative xpath
syntax:
//*[@attribute='value']
here "*" represents any tagname
ex:
//*[@name='identifier']

Finding Relative xpath for a webelement using Firepath

Right click on any element
Click on "Inspect in FirePath"
Ensure "Generate Absolute Xpath" is uncheked under FirePath Dropdown
Relative xpath is generated successfully

NOTE: Unchecked "Generate Absolute Xpath" is used to Generate "Relative Xpath"


ii. Providing multiple attribute values using Relative xpath
we can also give more than one attribute values to address a webelement

syntax:
//tagname[@attribute1='value'][@attribute2='value']

Exp:
//input[@name='identifier'][@type='email']
or
//*[@name='identifier'][@type='email']

iii. Using text():
Used to identify a webelement through visibletext
syntax:
//tagname[text()='visibletext']

Exp:
//span[text()='Forgot email?']

iv. **traversing xpath:
It is a combination of relative xpath and absolute xpath
In following scenarios Traversing xpath is prefered
a. When there are similar objects exist in a page
b. When webelement properties are changing during runtime (i.e. Dynamic objects)

Exp: Finding traversing xpath for "signin" object in www.amazon.in"

//div[@id='rhf-container']/div/div[3]/div/a/span

Exp: Finding traversing xpath for "6E senior citizen" webelement in www.goindigo.in

//div[@id='oneWay']/form/div/div/div/ul/li[3]/div/label

Exp: Finding traversing xpath for "New pwd" edit box based on create account section
in a FB-home page

//div[@id='reg_form_box']/div[5]/div/div/input

8. cssSelector:
Cascading Style Sheet
Used to identify the webelements which doesn't have proper attribute values

Syntax:
driver.findElement(By.cssSelector(value));

cssSelector syntax:
tagname[attribute='value']

Exp:
input[id='identifierId']
or
tagname[text()='visibletext']

Exp:
span[text()='Next'] //for "Next" button in "Gmail-home page"

NOTE:   CssSelector identification is much faster than xpath during Runtime,
        but xpath is prefered locator

Exp: Writing script to perform login operation on Salesforce application using xpath

/*Exercise:
  Launch FireFox Browser
  Open ("https://login.salesforce.com")
        Maximize the browser window
  Enter username using xpath
  Enter password using xpath
  Click on Login using xpath*/


//To launch firefox browser
WebDriver driver= new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Enter username using xpath
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Enter password using xpath
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To Click on Login Button using xpath
driver.findElement(By.xpath("//input[@id='Login']")).click();

Exp: Writing script to perform login operation on mercury tours application using cssSelector


/*Exercise:
  Launch FireFox Browser
  Open ("https://login.salesforce.com")
        Maximize the browser window
  Enter username using cssSelector
  Enter password using cssSelector
  Click on Login using cssSelector*/


//To launch firefox browser
WebDriver driver= new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Enter username using cssSelector
driver.findElement(By.cssSelector("input[name='username']")).sendKeys("SeleniumClass");
//To Enter password using cssSelector
driver.findElement(By.cssSelector("input[name='password']")).sendKeys("Password");
//To Click on Login Button using cssSelector
driver.findElement(By.cssSelector("input[name='Login']")).click();