Java Basics:Break, Continue and return statements Example in Selenium webdriver
Break, Continue and return statements Example in Selenium webdriver
Branching statements will transfer the control from one statement to another statement. the following are branching statements in java programming
1. break
2. continue
3. return
1. break:
break statement is used to stop the execution and comes out of loop. Mostly break statement is used in switch in order to stop fall through and in loops also we use break.
Example
package com.seleniumeasy.controlstatements;
public class BreakDemo {
public static void main(String[] args) {
for(int i=1;i<=20;i++) {
System.out.println(i);
if(i==7)
break;
}
}
}
Let us checkout selenium example for this break statement: -
boolean bValueExists = false;
// For each option in the list, first verify if it's the one that you want and then click on it
for (WebElement option : listOptions) {
if (option.getText().contains(sOptionToSelect)) {
option.click();
System.out.println("Selected option from the list")
bValueExists = true;
break;
}
}
In the above example, If we don't use Break statement, it will try to check all the list values and then comes out of the for loop. If say there are list of 20 values, and the One which we are looking is at 2nd position. Now when the condition is satisfied, we should come out of the loop instead of verifying all the remaining 18 values from the list.
You can check here for more detailed examples with selenium
1) Working with Ajax / JQuery fields
2) Working with checkboxes etc
1) Working with Ajax / JQuery fields
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) Working with checkboxes
Working with Checkbox using Resuable 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;
}
}
}
}
2. Continue:
continue statement is also same as break statement the only difference is when break statement executes it comes out of loop where as continue comes out of loop and jumps to the conditional statement of loop. continue is used only in loops to jump from present iteration and executes for next iteration.
Example:
package com.seleniumeasy.controlstatements;
public class ContinueDemo {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
3. return:
return statements are used in methods which returns a value or statement from current to calling method. return statement must be always last statement in the method
Example:
package com.seleniumeasy.controlstatements;
public class ReturnDemo {
public static void main(String[] args) {
int c;
ReturnDemo rd =new ReturnDemo();
c=rd.add(10,20);
System.out.println(c);
}
public int add(int a, int b){
int c=a+b;
return c;
}
}
Let us look into the below simple selenium example of 'return' :-
/**
* This method is used to get the current url
* @return, returns current url
*/
public String getCurrentURL()
{
String strURL= null;
try {
strURL= driver.getCurrentUrl();
}
catch(Exception ex) {
System.out.println("Exception occured while getting the current url : "+ex.getStackTrace());
Assert.fail("Exception occured");
}
return strURL;
}
The above method is to get current URL of the application. 'driver.getCurrentUrl();' will return URL as string and the same string will be returned to the calling method.
When ever working in a framework, for most of the methods, you will find return statements which can be re-used for multiple times. Each time any method calls, it will try to return the value. You can check here for more examples on return statements. Where we have applied for
1) Working with Select examples, where some times we may return Boolean value like true/false
2) when working with Window popups etc.
1) Working with Select examples
Webdriver SELECT Methods to work with Dropdowns
WebDriver’s support classes called “Select”, which provides useful methods for interacting with select options. User can perform operations on a select dropdown and also de-select operation using the below methods.
Method Name: selectByIndex
Syntax: select.selectByIndex(Index);
Purpose: To Select the option based on the index given by the user.
There is an attribute called "values" which will have the index values.
The below is the sample html code using index
Example
HTML Code
<html>
<head>
<title>Select Example by Index value</title>
</head>
<body>
<select name="Mobiles"><option value="0" selected> Please select</option>
<option value="1">iPhone</option>
<option value="2">Nokia</option>
<option value="3">Samsung</option>
<option value="4">HTC</option>
<option value="5">BlackBerry</option>
</select>
</body>
</html>
Webdriver code for Selecting a Value using select.selectByValue(Value);
public class selectByIndexExample {
WebDriver driver;
@Test
public void selectSamples()
{
driver = new FirefoxDriver();
driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-samples\\Final Code\\chapter-07\\dropdown-select.html");
WebElement element=driver.findElement(By.name("Mobiles"));
Select se=new Select(element);
se.selectByIndex(1);
}
}
Method Name: selectByValue
Syntax: select.selectByValue(Value);
Purpose: To Select the options that have a value matching with the given argument by the user.
Example:
HTML Code:
<html>
<head>
<title>Select Example by Value</title>
</head>
<body>
<p>Which mobile device do you like most?</p>
<select name="Mobiles"><option selectd> Please select</option>
<option value="iphone">iPhone</option>
<option value="nokia">Nokia</option>
<option value="samsung">Samsung</option>
<option value="htc">HTC</option>
<option value="blackberry">BlackBerry</option>
</select>
</body>
</html>
Webdriver code for Selecting a Value using select.selectByValue(Value);
public class selectExamples {
WebDriver driver;
@Test
public void selectSamples()
{
driver = new FirefoxDriver();
driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-samples\\Final Code\\chapter-07\\dropdown-select.html");
WebElement element=driver.findElement(By.name("Mobiles"));
Select se=new Select(element);
se.selectByValue("nokia");
}
}
Method Name: selectByVisibleText
Syntax: select.selectByVisibleText(Text);
Purpose: To Select all options that display text matching the given argument. It will not look for any index or value, it will try to match the VisibleText (which will display in dropdown)
Example: Any of the above html code can be taken as example.
Webdriver example code to select the value by Visible text.
public class selectExamples {
WebDriver driver;
@Test
public void selectSamples()
{
driver = new FirefoxDriver();
driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-samples\\Final Code\\chapter-07\\dropdown-select.html");
WebElement element=driver.findElement(By.name("Mobiles"));
Select se=new Select(element);
se.selectByVisibleText("HTC");
}
}
Method Name: deselectByIndex
Syntax: select.deselectByIndex(Index);
Purpose: To Deselect the option at the given index. The user has to provide the value of index.
Please check for the below example.
Method Name: deselectByValue
Syntax: select.deselectByValue(Value);
Purpose: To Deselect all options that have a value matching the given argument.
Please check for the below example.
Method Name: deselectByVisibleText
Syntax: select.deselectByVisibleText(Text);
Purpose: To Deselect all options that display text matching the given argument.
Please check for the below example.
Method Name: deselectAll
Syntax: select.deselectAll();
Purpose: To Clear all selected entries. This works only when the SELECT supports multiple selections. It throws NotImplemented eError if the "SELECT" does not support multiple selections. In select it mandatory to have an attribute multiple="multiple"
Please check for the below example.
Example::
HTML Code for Multi Select :
<html>
<head>
<title>Multi select Drop Down List Box</title>
</head>
<body>
<p>What all devices do you listen to music on?</p>
<select name="Mobdevices" multiple="multiple"><option value="0" selectd> Please select</option>
<option value="1">iPhone</option>
<option value="2">Nokia</option>
<option value="3">Samsung</option>
<option value="4">HTC</option>
<option value="5">BlackBerry</option>
</select>
</body>
</html>
Webdriver code to show all the above deselect methods.
public class selectExamples {
WebDriver driver;
@Test
public void selectSamples() throws InterruptedException
{
driver = new FirefoxDriver();
driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-samples\\Final Code\\chapter-07\\dropdown-select.html");
WebElement element=driver.findElement(By.name("Mobdevices"));
Select se=new Select(element);
//Here we will take multi select dropdown to show you the difference
se.selectByVisibleText("HTC");
se.selectByValue("nokia");
//From the above two commands, in the dropdown two values will be selected.
//Now we will try to deselect any of the One
//Im using thread to see the difference when selecting and selecting
Thread.sleep(3000);
se.deselectByValue("nokia");
//You can deselect the value by specifying the index, value and VisibleText
//It will work if you the index is already selected
se.deselectByIndex(1);
//It will deselect if the visible text HTC is in selected mode
se.deselectByVisibleText("HTC");
//It will de-select all the values which are selected
se.deselectAll();
}
}
Webdriver Select with Multiple Attribute
WebDriver’s support classes called “Select”, which provides useful methods for interacting with select options. User can perform operations on a select dropdown and also de-select operation using the below methods.
User can also get the text of the values in the dropdown. Also can get the option which are selected by the user. To use these options, the Select Tag should have "multiple" attribute.
Method Name: getOptions
Syntax: select.getOptions ();
Returns: List
Purpose: Returns all the option elements displayed in this select tag (dropdown list)
Example:HTML Sample Code
<html>
<head>
<title>Multi select Drop Down List Box</title>
</head>
<body>
<p>What all devices do you listen to music on?</p>
<select name="Mobdevices" multiple="multiple"><option value="0" selected> Please select</option>
<option value="1">iPhone</option>
<option value="2">Nokia</option>
<option value="3">Samsung</option>
<option value="4">HTC</option>
<option value="5">BlackBerry</option>
</select>
</body>
</html>
Example Webdriver Code:
//To get all the options present in the dropdown
List<WebElement> allOptions = se.getOptions();
for (WebElement webElement : allOptions)
{
System.out.println(webElement.getText());
}
Method Name: getAllSelectedOptions
Syntax: select.getAllSelectedOptions();
Returns: List
Purpose: It will return all the option elements that are selected in the select tag.
Example Webdriver Code
WebElement element=driver.findElement(By.name("Mobdevices"));
Select se=new Select(element);
se.selectByVisibleText("Nokia");
se.selectByVisibleText("HTC");
//To get all the options that are selected in the dropdown.
List<WebElement> allSelectedOptions = se.getAllSelectedOptions();
for (WebElement webElement : allSelectedOptions)
{
System.out.println("You have selected ::"+ webElement.getText());
}
Method Name: getFirstSelectedOption
Syntax: Select.getFirstSelectedOption();
Returns: WebElement
Purpose: It will return the first selected option in this select tag (or the currently selected option in a normal select)
Example Webdriver Code:
WebElement element=driver.findElement(By.name("Mobdevices"));
Select se=new Select(element);
se.selectByVisibleText("Nokia");
se.selectByVisibleText("HTC");
//To get the first selected option in the dropdown
WebElement firstOption = se.getFirstSelectedOption();
System.out.println("The First selected option is::" +firstOption.getText());
Method Name: isMultiple
Syntax: select.isMultiple ();
Returns: Boolean
Purpose: To check whether the Select element supports selecting multiple options. This will be done by checking the value of the "multiple" attributes in Select tag.
Example:
if(se.isMultiple())
{
System.out.println("Select tag allows multiple selection");
}
else
{
System.out.println("Select does not allow multiple selections");
}
The below example Webdriver code show all the above examples together
package com.first.example;
import java.util.Iterator;
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.Select;
import org.testng.annotations.Test;
public class selectExamples {
WebDriver driver;
@Test
public void selectSamples() throws InterruptedException
{
driver = new FirefoxDriver();
driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-samples\\Final Code\\chapter-07\\dropdown-select.html");
WebElement element=driver.findElement(By.name("Mobdevices"));
Select se=new Select(element);
se.selectByVisibleText("Nokia");
se.selectByVisibleText("HTC");
//To get all the options present in the dropdown
List<WebElement> allOptions = se.getOptions();
for (WebElement webElement : allOptions)
{
System.out.println(webElement.getText());
}
//To get all the options that are selected in the dropdown.
List<WebElement> allSelectedOptions = se.getAllSelectedOptions();
for (WebElement webElement : allSelectedOptions)
{
System.out.println("You have selected::"+ webElement.getText());
}
//To get the first selected option in the dropdown
WebElement firstOption = se.getFirstSelectedOption();
System.out.println("The First selected option is::" +firstOption.getText());
if(se.isMultiple())
{
System.out.println("Select tag allows multiple selection");
}
}
}
_____________________________
2) Working with Window popups
Handle windows popups using Selenium Webdriver
There are many cases, where a application displays multiple windows when you open a website. Those are may be advertisements or may be a kind of information showing on popup windows. We can handle multiple windows using Windows Handlers in selenium webdriver.
Step 1: After opening the website, we need to get the main window handle by using driver.getWindowHandle();
The window handle will be in a form of lengthy alpha numeric
Step 2: We now need to get all the window handles by using driver.getWindowHandles();
Step 3: We will compare all the window handles with the main Window handles and perform the operation the window which we need.
The below example shows how to handle multiple windows and close all the child windows which are not need. We need to compare the main window handle to all the other window handles and close them.
package com.pack;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class WindowExamples {
static WebDriver driver;
@Test
public void test_CloseAllWindowsExceptMainWindow() {
driver = new FirefoxDriver();
// It will open Naukri website with multiple windows
driver.get("http://www.naukri.com/");
// To get the main window handle
String windowTitle= getCurrentWindowTitle();
String mainWindow = getMainWindowHandle(driver);
Assert.assertTrue(closeAllOtherWindows(mainWindow));
Assert.assertTrue(windowTitle.contains("Jobs - Recruitment"), "Main window title is not matching");
}
public String getMainWindowHandle(WebDriver driver) {
return driver.getWindowHandle();
}
public String getCurrentWindowTitle() {
String windowTitle = driver.getTitle();
return windowTitle;
}
//To close all the other windows except the main window.
public static boolean closeAllOtherWindows(String openWindowHandle) {
Set<String> allWindowHandles = driver.getWindowHandles();
for (String currentWindowHandle : allWindowHandles) {
if (!currentWindowHandle.equals(openWindowHandle)) {
driver.switchTo().window(currentWindowHandle);
driver.close();
}
}
driver.switchTo().window(openWindowHandle);
if (driver.getWindowHandles().size() == 1)
return true;
else
return false;
}
}
The below image will show you the multiple windows that open in the application. It has now open total of three windows (One is main window and other two are child windows)
The below image will show the multiple window handlers for child windows and main window. We will have all the window handles in one set and we use each of them to compare and perform operation on the required window.
The below is the output of the program:
{2b2577c4-bf92-4392-a93f-b0428a3d9aab}
Naukri.com – Jobs – Jobs in India – Recruitment – Job Search – Employment – Job Vacancies
it is the main window
Naukri.com – Jobs – Jobs in India – Recruitment – Job Search – Employment – Job Vacancies
Barclays
Naukri.com – Jobs – Jobs in India – Recruitment – Job Search – Employment – Job Vacancies
HCL
Naukri.com – Jobs – Jobs in India – Recruitment – Job Search – Employment – Job Vacancies
_______
Perform operations on new window
There are cases where we need to open new window and perform operations or there may be cases where after clicking on any button / link, it opens new window and need to perform operations on the new window.
Let us look into such example:
Test case: We need to open 'http://linkedin.com' and click on 'Help Center' link at the bottom which will open new window.
1. Verify the title of the new window
2. Verify text 'Welcome' on the page.
3. Search for a Question with text "Frequently Asked Questions" and verify the result.
package com.pack;
import java.util.Set;
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.Assert;
import org.testng.annotations.Test;
public class WindowExamples {
public static WebDriver driver;
@Test
public void verifySearchInNewWindow() throws InterruptedException {
driver = new FirefoxDriver();
driver.navigate().to("http://linkedin.com/");
driver.manage().window().maximize();
String mainHandle = driver.getWindowHandle();
//Wait for the element to be present
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".cust-svc-link")));
driver.findElement(By.linkText("Help Center")).click();
//Switch to new window and verify the title
waitForNewWindowAndSwitchToIt(driver);
String newTitle = getCurrentWindowTitle();
Assert.assertEquals(newTitle, "LinkedIn Help Center", "New window title is not matching");
//Verify the text present on the page
String textOnpage=driver.findElement(By.cssSelector(".welcome")).getText().trim();
Assert.assertEquals(textOnpage, "Welcome!");
//Verify search text on the page
String searchText="Frequently Asked Questions";
WebElement searchInputBox=driver.findElement(By.id("kw"));
searchInputBox.sendKeys(searchText);
WebElement searchButton = driver.findElement(By.cssSelector(".button.leftnoround.blue"));
searchButton.click();
WebElement resultedElement = driver.findElement(By.cssSelector(".rn_Element2"));
String resultedText = resultedElement.getText().trim();
System.out.println(resultedText);
Assert.assertTrue(resultedText.contains(searchText), "Search successfull");
closeAllOtherWindows(driver, mainHandle);
}
To execute the above test we have created a methods which can be reused with multiple tests.
Below method is used to get the main window handle. we will the driver as parameter.
public static String getMainWindowHandle(WebDriver driver) {
return driver.getWindowHandle();
}
Below method is used to get the current window title
public static String getCurrentWindowTitle() {
String windowTitle = driver.getTitle();
return windowTitle;
}
Below method is used to close all the other windows except the main window.
public static boolean closeAllOtherWindows(WebDriver driver, String openWindowHandle) {
Set<String> allWindowHandles = driver.getWindowHandles();
for (String currentWindowHandle : allWindowHandles) {
if (!currentWindowHandle.equals(openWindowHandle)) {
driver.switchTo().window(currentWindowHandle);
driver.close();
}
}
driver.switchTo().window(openWindowHandle);
if (driver.getWindowHandles().size() == 1)
return true;
else
return false;
}
Below method is used to wait for the new window to be present and switch to it.
public static void waitForNewWindowAndSwitchToIt(WebDriver driver) throws InterruptedException {
String cHandle = driver.getWindowHandle();
String newWindowHandle = null;
Set<String> allWindowHandles = driver.getWindowHandles();
//Wait for 20 seconds for the new window and throw exception if not found
for (int i = 0; i < 20; i++) {
if (allWindowHandles.size() > 1) {
for (String allHandlers : allWindowHandles) {
if (!allHandlers.equals(cHandle))
newWindowHandle = allHandlers;
}
driver.switchTo().window(newWindowHandle);
break;
} else {
Thread.sleep(1000);
}
}
if (cHandle == newWindowHandle) {
throw new RuntimeException(
"Time out - No window found");
}
}
}
Note: When ever we work on multiple windows, switching plays major role. We should switch to the desired window to perform operations and again switch back to default window to work on main window.
Comments
Post a Comment