August 3, 2015

Check all check boxes and verify status of check box

One more example from dave haeffner's weekly tip...

The Problem

Checkboxes, an often used element in web applications. But how do you work with them in your Selenium tests? Intuitively you may reach for a method that has the word 'checked' in it -- like .checked? or .isChecked. But this doesn't exist in Selenium. So how do you do it?

A Solution

There are two ways to approach this -- through an element's 'checked' attribute (a.k.a. an attribute lookup), or by asking the element if it is selected.
boolean org.openqa.selenium.WebElement.isSelected()

  • isSelected

    boolean isSelected()
    Determine whether or not this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
    Returns:
    True if the element is currently selected or checked, false otherwise.
Below example shows you how to check all check boxes and verify the status of check boxes.




package sample;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Checkboxes_Test {
 public WebDriver driver;

 @Test
 public void testCheckboxes_Test() throws Exception {

  driver.get("http://the-internet.herokuapp.com");
  driver.findElement(By.linkText("Checkboxes")).click();
  //get all the check boxes in web page
  List<WebElement> cBox=driver.findElements(By.cssSelector("input[type='checkbox']"));
  for (int i = 0; i < cBox.size(); i++) {
   //verify check box status, if it is not checked then perform click operation
   if (!cBox.get(i).isSelected()) {
    cBox.get(i).click();
    System.out.println("Check box "+ i + " status is :"+cBox.get(i).isSelected());
   }
   else
   {
    System.out.println("Check box "+ i + " is already selected and status is :"+cBox.get(i).isSelected());
   }
  }
 }

 @BeforeClass
 public void beforeClass() {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 }

 @AfterClass
 public void afterClass() throws Exception {
  driver.quit();
 }

}

1 comment:

  1. Thanks for sharing this information.It was very nice blog to learn about Selenium

    ReplyDelete