Java Basics:Do While,For Loop Examples in Selenium
do..while loop
while and do..while loops, both are same . the only difference is while loop checks the conditional expression first and if it is true then executes statement. where as do while first executes the statement then checks for the conditional expression.
Syntax:
do{
statements;
}while(boolean_expression);
Example:
package com.seleniumeasy.controlstatements;
public class DoWhileDemo {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Here in do while first it prints the i value for the first time and then check for condition and if it evaluates to true then statements inside do while loop will execute for second time and this process continuous until the conditional expression returns to false once it evaluates to false then comes out of the loop.
In do..while loop where the conditional expression is true or false, statements in side loop will executes at-least for once.
for loop
for loop is the famous and most commonly used loop in java programming.
Syntax:
for(initialization;boolean_expression;increment_decrement){
statements;
}
In for loop, initializing the value, checking for condition and increment or decrement comes in single step.
Example:
package com.seleniumeasy.controlstatements;
public class ForLoopDemo {
public static void main(String[] args) {
for(int i=0;i<10;i++){
System.out.println(i);
}
}
}
In the above program initialization part will execute first and only for once and next condition will be checked and if the condition is evaluated to true, statements inside for loop will be executed and then incrementation operation will be performed and once again now goes to checking for condition and if it evaluates to true statements executed this process will repeat until the conditional expression becomes false . once this becomes false it comes out of loop.
In the initialization part we can declare more than one value but it should be of same type
Example:
for(int i=1,j=1; i<10; j++)
for-each loop(enhanced for loop):
for-each loop is introduced in java 1.5v.
this loop is mainly used to retrieving the elements in array and collections
Syntax:
for(declaration:expression){
statements;
}
Example:
package com.seleniumeasy.controlstatements;
public class ForEachDemo {
public static void main(String[] args) {
int a[]={1,2,3,4,5,6,7,8,9,10};
for(int i:a){
System.out.println(i);
}
}
}
Let us now use for-each loop in selenium in the blow example:
boolean flag = false;
List<WebElement> listBoxItems = driver.findElements(By.tagName("li"));
for(WebElement item : listBoxItems)
{
if(item.getText().equals(value))
flag=true;
break;
}
In the above example, we are first getting the list of WebElements. driver.findElements statement returns list of webElements. Now from that list, first we will loop each element and get the text to compare with value. If the values is equal we will make the 'flag' to true.
We use this at many places like '
1) Select a value from list,
2) Selecting a desired date from calendar
3)To select a check from multiple checkboxes
where you list of items/elements and then do what ever you want once you find the one which you are looking for.
1) Select a value from list
Now a days, in most of the applications, we can see a 'Auto Complete' textboxes which will help users to quickly find the option from a pre-populated list of values based on the text that is entered by the user. It mainly concentrates on providing suggestions to users while typing into the field.
Let us now see a basic example. When we enter any text, we can select the value from the pre-populated list by using 'String' or 'Index value'
package com.pack.auto;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class AutoCompleteExample {
WebDriver driver;
WebDriverWait wait;
String URL = "http://jqueryui.com/autocomplete/";
private By frameLocator = By.className("demo-frame");
private By tagText = By.id("tags");
@BeforeClass
public void Setup() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
@Test
public void rightClickTest() {
driver.navigate().to(URL);
WebElement frameElement=driver.findElement(frameLocator);
driver.switchTo().frame(frameElement);
wait.until(ExpectedConditions.presenceOfElementLocated(tagText));
WebElement textBoxElement = driver.findElement(tagText);
textBoxElement.sendKeys("a");
selectOptionWithText("Java");
//selectOptionWithIndex(2);
}
Below is the code to select the Option based on the string passed in the Test. We are List
public void selectOptionWithText(String textToSelect) {
try {
WebElement autoOptions = driver.findElement(By.id("ui-id-1"));
wait.until(ExpectedConditions.visibilityOf(autoOptions));
List<WebElement> optionsToSelect = autoOptions.findElements(By.tagName("li"));
for(WebElement option : optionsToSelect){
if(option.getText().equals(textToSelect)) {
System.out.println("Trying to select: "+textToSelect);
option.click();
break;
}
}
} catch (NoSuchElementException e) {
System.out.println(e.getStackTrace());
}
catch (Exception e) {
System.out.println(e.getStackTrace());
}
}
Below is the method to select Option based on the index value. We need to pass the index value to select the required value. If you are not specific to the value, we can just select first value always.
public void selectOptionWithIndex(int indexToSelect) {
try {
WebElement autoOptions = driver.findElement(By.id("ui-id-1"));
wait.until(ExpectedConditions.visibilityOf(autoOptions));
List<WebElement> optionsToSelect = autoOptions.findElements(By.tagName("li"));
if(indexToSelect<=optionsToSelect.size()) {
System.out.println("Trying to select based on index: "+indexToSelect);
optionsToSelect.get(indexToSelect).click();
}
}
catch (NoSuchElementException e) {
System.out.println(e.getStackTrace());
}
catch (Exception e) {
System.out.println(e.getStackTrace());
}
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
- _______________________________________
- 2) Selecting a desired date from calendar
JQuery And KendoUI Date Picker Calendar example
we will see how to work with Date Picker by taking different calendars. We will take three different calendars and see how to work with them. There are different date pickers used in applications example JQuery date picker, KendoUI date picker etc.
Some date pickers display previous or next month dates also depends on the month. And in these cases, how should we work. When ever we work with calendar, it is very important in identifying the locators. Based on our requirement we can define simple xpath to work with calendar.
Let us see such example first by taking a calendar which looks like above.
@Test
public void jQueryCalendarMultipleMonths() {
driver.navigate().to("http://jqueryui.com/resources/demos/datepicker/other-months.html");
WebElement calElement=driver.findElement(By.id("datepicker"));
calElement.click();
selectDatefromMultiDate("30");
}
Method selectDateFromMultiCalendar() looks like below. It has a single and simple xpath to select desired date from date picker.
public void selectDatefromMultiDate(String date) {
By calendarXpath=By.xpath("//td[not(contains(@class,'ui-datepicker-other-month'))]/a[text()='"+date+"']");
//By calendarXpath=By.xpath("table//td/a[text()='"+date+"']");
driver.findElement(calendarXpath).click();
}
In the above method, if you observe we have defined xpath to make our script to click on date. As said if there are previous month dates are also displayed, you will have multiple dates. Look at the below example, it has 29 and 30 of previous month dates and '1' and '2' of the next month and the current month dates.
By calendarXpath=By.xpath("table//td/a[text()='"+date+"']");
If we use above xpath path and try to select '29' or '30', it will select the first element i.e previous month not the current month.
So in order to make sure we select the current month date, we should modify the xpath as below.
xpath = //td[not(contains(@class,'ui-datepicker-other-month'))]/a[text()='"+date+"']
Now let us see the other way of working with date picker with KendoUI Calendar.
@Test
public void kendoCalendarExample() {
driver.navigate().to(kendoURL);
WebElement calIcon=driver.findElement(By.cssSelector(".k-icon.k-i-calendar"));
calIcon.click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("datetimepicker_dateview")));
System.out.println("Calendar Found");
selectKendoDate("10");
}
public void selectKendoDate(String date) {
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("k-content")));
WebElement table = driver.findElement(By.className("k-content"));
System.out.println("Kendo Calendar");
List<WebElement> tableRows = table.findElements(By.xpath("//tr"));
for (WebElement row : tableRows) {
List<WebElement> cells = row.findElements(By.xpath("td"));
for (WebElement cell : cells) {
if (cell.getText().equals(date)) {
driver.findElement(By.linkText(date)).click();
}
}
}
}
Here is an other example working with JQuery Date picker.
@Test
public void jQueryCalendarExample() {
driver.navigate().to(jQueryURL);
WebElement frameElement=driver.findElement(frameLocator);
driver.switchTo().frame(frameElement);
wait.until(ExpectedConditions.presenceOfElementLocated(tagText));
driver.findElement(tagText).click();
selectJQueryDate("21");
}
public void selectJQueryDate(String date) {
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("ui-datepicker-div")));
WebElement table = driver.findElement(By.className("ui-datepicker-calendar"));
System.out.println("JQuery Calendar Dates");
List<WebElement> tableRows = table.findElements(By.xpath("//tr"));
for (WebElement row : tableRows) {
List<WebElement> cells = row.findElements(By.xpath("td"));
for (WebElement cell : cells) {
if (cell.getText().equals(date)) {
driver.findElement(By.linkText(date)).click();
}
}
}
}
Hope the examples helps you. Feel free to comment you query or issue if you get any.
3) To select a check from multiple checkboxes
Working with Checkbox using Reusable Methods
Working with checkbox is very simple using webdriver. It is same as click operation. But it is always recommended to check if that is already in selected mode or deselected. Because, if it is already selected and when you click on the same element it will get deselected. We will look into different ways to perform select and de-select operations on checkboxes. We will also use reusable methods to perform the operation in multiple tests.
The below is the simple command to do that:
WebElement checkBoxElement=driver.findElement(By.id("persist_box"));
checkBoxElement.click();
I will try to explain you both select and de-select with the sample code:
package com.pack.methods;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
public class CheckBoxExample {
private WebDriver driver;
private String basePageURL;
@Test
public void testCaseToCheck() {
driver = new FirefoxDriver();
driver.get(basePageURL);
WebElement checkBoxElement=driver.findElement(By.id("persist_box"));
//Wait for the checkbox element to be visible
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(checkBoxElement));
Select_The_Checkbox(checkBoxElement);
}
@Test
public void testCaseToUnCheck() {
driver.navigate().to(basePageURL);
WebElement checkBoxElement=driver.findElement(By.id("persist_box"));
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(checkBoxElement));
DeSelect_The_Checkbox(checkBoxElement);
}
@Test
public void testCaseToCheckDesired(){
driver.navigate().to("someother page");
WebElement element = driver.findElement(By.cssSelector(".display"));
Select_The_CheckBox_from_List(element, "soccer");
}
In the above program, we have used reusable methods to select, deselect and select a particular value from multiple checkboxes. It is always better to have resubale to methods, so that we can resuse the same methods in multiple tests instead of writing the same code in multiple tests to perform the same operation.
Select_The_Checkbox(checkBoxElement);
DeSelect_The_Checkbox(checkBoxElement);
Select_The_CheckBox_from_List(element, "soccer");
Below are the resuable methods that are used in the above example code. You can write these methods in a separate class called generics or utils class where you can have all the resuable methods like below
Below method is used to Select a Checkbox, if it is not selected already
public void Select_The_Checkbox(WebElement element) {
try {
if (element.isSelected()) {
System.out.println("Checkbox: " + element + "is already selected");
} else {
// Select the checkbox
element.click();
}
} catch (Exception e) {
System.out.println("Unable to select the checkbox: " + element);
}
}
Below method is used to De-select a Checkbox, if it is selected already
public void DeSelect_The_Checkbox(WebElement element) {
try {
if (element.isSelected()) {
//De-select the checkbox
element.click();
} else {
System.out.println("Checkbox: "+element+"is already deselected");
}
} catch (Exception e) {
System.out.println("Unable to deselect checkbox: "+element);
}
}
Below method is used to select the checkbox with the specified value from multiple checkboxes.
public void Select_The_CheckBox_from_List(WebElement element, String valueToSelect) {
List<WebElement> allOptions = element.findElements(By.tagName("input"));
for (WebElement option : allOptions) {
System.out.println("Option value "+option.getText());
if (valueToSelect.equals(option.getText())) {
option.click();
break;
}
}
}
}
Comments
Post a Comment