Monday, March 20, 2023

Dropdown Handling with Selenium WebDriver: Tips and Techniques

 import java.time.Duration;

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Collectors;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Example {

WebDriver driver;

@BeforeTest

public void setUp() {

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.manage().window().maximize();

driver.get("https://www.amazon.com/");

}

@Test

public void dropdownTest() {

WebElement dropdown = driver.findElement(By.id("searchDropdownBox"));

Select select = new Select(dropdown);

// Print the first selected option and assert if it equals “All Departments”.

String firstSelectedOption = select.getFirstSelectedOption().getText();

System.out.println("firstSelectedOption = " + firstSelectedOption);

if (firstSelectedOption.equals("All Departments")) {

System.out.println("PASS");

} else {

System.out.println("FAIL");

}

// Print all of the drop down options-getOptions(); method returns the List<WebElement>. 

Using a loop, print all options.

List<WebElement> allOptions = select.getOptions();

for (WebElement eachOption : allOptions) {

System.out.println(eachOption.getText());

}

// Print the total number of options in the dropdown

int totalNumOfOptions = select.getOptions().size();

System.out.println("numOfOptions = " + totalNumOfOptions);

// if ‘Appliances’ is a drop-down option. Print true if “Appliances” is

// an option. Print false otherwise.

List<String> listOfOptions = new ArrayList<>();

for (WebElement eachOption : allOptions) {

listOfOptions.add(eachOption.getText());

}

System.out.println("listOfOptions = " + listOfOptions);

if (listOfOptions.contains("Appliances")) {

System.out.println("TRUE");

} else {

System.out.println("FALSE");

}

// Assert if the dropdown is in Alphabetical Order

List<String> sortedList = listOfOptions.stream().sorted().collect(Collectors.toList());

System.out.println("sortedList = " + sortedList);

}

@AfterTest

public void tearDown() {

driver.quit();

}

}

No comments:

Post a Comment