Monday, June 10, 2024

How to Handle Checkboxes in Selenium

 package com.system.patternz;

import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Practice {
WebDriver driver;

@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://testautomationpractice.blogspot.com/");
driver.manage().window().maximize();
}

@Test(enabled = true, priority = 0, description = "how to select specific checkboxes")
public void test1() throws InterruptedException {
driver.findElement(By.id("sunday")).click();
Thread.sleep(3000);
}

@Test(enabled = true, priority = 1, description = "how to select all checkboxes")
public void test2() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
for (WebElement x : list) {
x.click();
}
}

@Test(enabled = true, priority = 2, description = "how to select multiple checkboxes by choice")
public void test3() throws InterruptedException {
ArrayList<String> list3 = new ArrayList<String>();
list3.add("Sunday");
list3.add("Wednesday");
list3.add("Saturday");
System.out.println(list3);
List<WebElement> list1 = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
for (WebElement x : list1) {
String str = x.getText();
for (String x1 : list3) {
if (str.equals(x1)) {
x.click();
Thread.sleep(3000);
}
}
}
}

@Test(enabled = true, priority = 3, description = "how to select multiple checkboxes by choice")
public void test4() throws InterruptedException {
List<WebElement> list1 = driver.findElements(By.xpath("//*[@class='form-group'][4]//div//input"));
for (WebElement x : list1) {
String str = x.getAttribute("id");
if (str.equals("monday") || str.equals("wednesday") || str.equals("saturday")) {
System.out.println("next click");
x.click();
Thread.sleep(3000);
} else {
System.out.println("not found");
}
}
}

@Test(enabled = true, priority = 4, description = "how to select last 2 checkboxes")
public void test5() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
int totalcheckboxes = list.size();
for (int i = totalcheckboxes - 2; i < totalcheckboxes; i++) {
list.get(i).click();
}
}

@Test(enabled = true, priority = 5, description = "how to select first 2 checkboxes")
public void test6() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
int totalcheckboxes = list.size();
for (int i = 0; i < totalcheckboxes; i++) {
if (i < 2) {
list.get(i).click();
Thread.sleep(3000);
}
}
}
}

No comments:

Post a Comment